#!/bin/bash
#
# Pre-commit hook for JCL
#
# This hook runs automatically before each commit to ensure code quality.
# It performs the following checks:
#   1. Code formatting (cargo fmt)
#   2. Linting (cargo clippy)
#   3. Tests (cargo test)
#
# To bypass this hook temporarily, use: git commit --no-verify
#

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

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

# Check 1: Format code
echo "📝 [1/3] Formatting code with cargo fmt..."
if cargo fmt --all -- --check > /dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} Code is properly formatted"
else
    echo -e "${YELLOW}⚠${NC}  Code needs formatting, auto-formatting now..."
    cargo fmt --all
    echo -e "${GREEN}✓${NC} Code formatted successfully"
fi

# Check 2: Run clippy
echo ""
echo "🔍 [2/3] Running clippy..."
# Note: We check clippy but don't fail on warnings since there are existing warnings in the codebase
# This ensures clippy runs but doesn't block commits due to pre-existing issues
if cargo clippy --lib --tests --bins --all-features 2>&1 | grep -q "error:"; then
    echo -e "${RED}✗${NC} Clippy found errors. Please fix them before committing."
    echo ""
    cargo clippy --lib --tests --bins --all-features
    exit 1
else
    # Check for warnings but don't fail
    if cargo clippy --lib --tests --bins --all-features 2>&1 | grep -q "warning:"; then
        echo -e "${YELLOW}⚠${NC}  Clippy warnings found (not blocking commit)"
    else
        echo -e "${GREEN}✓${NC} No clippy warnings"
    fi
fi

# Check 3: Run tests
echo ""
echo "🧪 [3/3] Running tests..."
if cargo test --quiet --lib --bins --tests 2>&1; then
    echo -e "${GREEN}✓${NC} All tests passed"
else
    echo -e "${RED}✗${NC} Tests failed. Please fix failing tests before committing."
    exit 1
fi

echo ""
echo -e "${GREEN}✓ All pre-commit checks passed!${NC}"
echo ""

exit 0
