#!/bin/sh
#
# Pre-commit hook: Format and lint checks
# Runs before each commit to ensure code quality
#

set -e

echo "🔍 Running pre-commit checks..."

# Check if cargo is available
if ! command -v cargo &> /dev/null; then
    echo "❌ cargo not found. Please install Rust."
    exit 1
fi

# Format check
echo "📝 Checking formatting..."
if ! cargo fmt --all -- --check; then
    echo ""
    echo "❌ Formatting issues found!"
    echo "   Run 'cargo fmt --all' to fix them."
    exit 1
fi
echo "✅ Formatting OK"

# Clippy lints
echo "📎 Running Clippy..."
if ! cargo clippy --all-targets --all-features -- -D warnings; then
    echo ""
    echo "❌ Clippy found issues!"
    echo "   Please fix the warnings above."
    exit 1
fi
echo "✅ Clippy OK"

# Check for common issues in staged files
echo "🔎 Checking for debug artifacts..."

# Get list of staged Rust files (skip if none)
STAGED_RS_FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.rs' 2>/dev/null || true)

if [ -n "$STAGED_RS_FILES" ]; then
    # Check for dbg! macro
    DBG_FILES=$(echo "$STAGED_RS_FILES" | xargs grep -l "dbg!" 2>/dev/null || true)
    if [ -n "$DBG_FILES" ]; then
        echo ""
        echo "⚠️  Warning: Found 'dbg!' macro in staged files:"
        echo "$DBG_FILES" | sed 's/^/   /'
        echo "   Consider removing debug statements before committing."
    fi

    # Check for println! outside examples/tests
    PRINTLN_FILES=$(echo "$STAGED_RS_FILES" | grep -v "^examples/" | grep -v "^tests/" | xargs grep -l "println!" 2>/dev/null || true)
    if [ -n "$PRINTLN_FILES" ]; then
        echo ""
        echo "⚠️  Warning: Found 'println!' in staged files (outside examples/tests):"
        echo "$PRINTLN_FILES" | sed 's/^/   /'
        echo "   Consider using proper logging instead."
    fi
fi

echo ""
echo "✅ All pre-commit checks passed!"

