#!/bin/bash
# pre-commit
# Git pre-commit hook that enforces AutoWorkflow rules
# Install: cp hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit

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

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔒 AUTOWORKFLOW PRE-COMMIT CHECK"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

BLOCKED=0

# Get list of staged files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E "\.(ts|tsx|js|jsx)$" || true)

# ─────────────────────────────────────────────────────────────
# Check 1: TypeScript Errors
# ─────────────────────────────────────────────────────────────

echo "📋 [1/5] TypeScript check..."

TSC_OUTPUT=$(npm run typecheck 2>&1) || true

if echo "$TSC_OUTPUT" | grep -q "error TS"; then
    ERROR_COUNT=$(echo "$TSC_OUTPUT" | grep -c "error TS" || echo "0")
    echo -e "${RED}   ⛔ Found $ERROR_COUNT TypeScript error(s)${NC}"
    echo ""
    echo "$TSC_OUTPUT" | grep "error TS" | head -10
    if [ "$ERROR_COUNT" -gt 10 ]; then
        echo "   ... and $(($ERROR_COUNT - 10)) more"
    fi
    BLOCKED=1
else
    echo -e "${GREEN}   ✓ No TypeScript errors${NC}"
fi

# ─────────────────────────────────────────────────────────────
# Check 2: ESLint Warnings
# ─────────────────────────────────────────────────────────────

echo ""
echo "📋 [2/5] ESLint check..."

LINT_OUTPUT=$(npm run lint 2>&1) || true

if echo "$LINT_OUTPUT" | grep -qE "[0-9]+ error|[0-9]+ warning"; then
    echo -e "${RED}   ⛔ ESLint issues found${NC}"
    echo "$LINT_OUTPUT" | grep -E "error|warning" | head -10
    BLOCKED=1
else
    echo -e "${GREEN}   ✓ No ESLint issues${NC}"
fi

# ─────────────────────────────────────────────────────────────
# Check 3: TODO/FIXME Comments
# ─────────────────────────────────────────────────────────────

echo ""
echo "📋 [3/5] TODO/FIXME check..."

if [ -n "$STAGED_FILES" ]; then
    TODO_FILES=$(echo "$STAGED_FILES" | xargs grep -l "TODO\|FIXME\|XXX\|HACK" 2>/dev/null || true)
    if [ -n "$TODO_FILES" ]; then
        echo -e "${RED}   ⛔ Found TODO/FIXME comments in:${NC}"
        echo "$TODO_FILES" | while read file; do
            echo "      - $file"
            grep -n "TODO\|FIXME\|XXX\|HACK" "$file" 2>/dev/null | head -3 | sed 's/^/        /'
        done
        BLOCKED=1
    else
        echo -e "${GREEN}   ✓ No TODO/FIXME comments${NC}"
    fi
else
    echo -e "${GREEN}   ✓ No TODO/FIXME comments${NC}"
fi

# ─────────────────────────────────────────────────────────────
# Check 4: Console.log Statements
# ─────────────────────────────────────────────────────────────

echo ""
echo "📋 [4/5] console.log check..."

if [ -n "$STAGED_FILES" ]; then
    CONSOLE_FILES=$(echo "$STAGED_FILES" | xargs grep -l "console\.\(log\|debug\|info\)" 2>/dev/null || true)
    if [ -n "$CONSOLE_FILES" ]; then
        echo -e "${RED}   ⛔ Found console.log statements in:${NC}"
        echo "$CONSOLE_FILES" | while read file; do
            echo "      - $file"
            grep -n "console\.\(log\|debug\|info\)" "$file" 2>/dev/null | head -3 | sed 's/^/        /'
        done
        BLOCKED=1
    else
        echo -e "${GREEN}   ✓ No console.log statements${NC}"
    fi
else
    echo -e "${GREEN}   ✓ No console.log statements${NC}"
fi

# ─────────────────────────────────────────────────────────────
# Check 5: Circular Dependencies (if madge available)
# ─────────────────────────────────────────────────────────────

echo ""
echo "📋 [5/5] Circular dependencies check..."

if command -v npx &> /dev/null && [ -d "src" ]; then
    CYCLES=$(npx madge --circular --extensions ts,tsx src/ 2>/dev/null || true)
    if [ -n "$CYCLES" ] && ! echo "$CYCLES" | grep -q "No circular"; then
        echo -e "${RED}   ⛔ Circular dependencies found:${NC}"
        echo "$CYCLES" | head -10
        BLOCKED=1
    else
        echo -e "${GREEN}   ✓ No circular dependencies${NC}"
    fi
else
    echo -e "${YELLOW}   ○ Skipped (madge not available or no src/)${NC}"
fi

# ─────────────────────────────────────────────────────────────
# Result
# ─────────────────────────────────────────────────────────────

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ $BLOCKED -eq 1 ]; then
    echo -e "${RED}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${RED}║                    ⛔ COMMIT BLOCKED ⛔                       ║${NC}"
    echo -e "${RED}╠══════════════════════════════════════════════════════════════╣${NC}"
    echo -e "${RED}║  Fix the issues above before committing.                     ║${NC}"
    echo -e "${RED}║                                                              ║${NC}"
    echo -e "${RED}║  Quick fixes:                                                ║${NC}"
    echo -e "${RED}║    npm run lint:fix     Auto-fix ESLint issues               ║${NC}"
    echo -e "${RED}║    npm run typecheck    See all TypeScript errors            ║${NC}"
    echo -e "${RED}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
    exit 1
fi

echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║                    ✅ ALL CHECKS PASSED                       ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
exit 0
