#!/bin/bash
# Pre-commit hook for comfygit-manager
# - Strips [tool.uv.sources] from pyproject.toml (prevents local dev paths from being committed)
# - Blocks mock API builds from being committed (most critical)
# - Checks that frontend build version matches pyproject.toml
# - Syncs requirements.txt from pyproject.toml dependencies
#
# Install: scripts/install-hooks.sh

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Handle both installed location (.git/hooks/) and source location (scripts/hooks/)
if [[ "$SCRIPT_DIR" == *".git/hooks"* ]]; then
    PROJECT_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")"
else
    PROJECT_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")"
fi

STRIP_SCRIPT="$PROJECT_ROOT/scripts/strip-dev-sources.py"

# Restore orphaned backup from previously aborted commit (if any)
python3 "$STRIP_SCRIPT" restore 2>/dev/null

# Strip [tool.uv.sources] if pyproject.toml is staged and has dev sources
if git diff --cached --name-only | grep -qE '^pyproject\.toml$'; then
    python3 "$STRIP_SCRIPT" strip
    git add "$PROJECT_ROOT/pyproject.toml"
fi

# Sync requirements.txt if pyproject.toml is staged
if git diff --cached --name-only | grep -qE '^pyproject\.toml$'; then
    echo "Syncing requirements.txt from pyproject.toml..."
    if command -v uv &> /dev/null; then
        (cd "$PROJECT_ROOT" && uv run scripts/sync-requirements.py)
        git add "$PROJECT_ROOT/requirements.txt"
        echo "requirements.txt updated and staged"
    else
        echo "Warning: uv not found, skipping requirements.txt sync"
    fi
fi

# Only run checks if frontend files are staged
if git diff --cached --name-only | grep -qE '^(pyproject\.toml|js/|frontend/)'; then
    JS_FILE="$PROJECT_ROOT/js/comfygit-panel.js"

    # Check for mock API enabled in built JS (most critical - check first)
    if [ -f "$JS_FILE" ]; then
        # When mock is disabled, isMockApi() compiles to: ==="true" (returns false for undefined)
        # When mock is enabled, it compiles to the full mock implementation (~55KB larger)
        # Simple heuristic: file size > 850KB likely has mock code bundled
        FILE_SIZE=$(wc -c < "$JS_FILE")
        if [ "$FILE_SIZE" -gt 950000 ]; then
            echo ""
            echo "ERROR: Frontend has mock API enabled!"
            echo "File size: $FILE_SIZE bytes (expected < 850KB without mock)"
            echo ""
            echo "Rebuild with mock disabled:"
            echo "  1. Set VITE_USE_MOCK_API=false in frontend/.env (or delete .env)"
            echo "  2. cd frontend && npm run build"
            exit 1
        fi
    fi

    # Check version match
    echo "Checking frontend version..."
    if ! "$PROJECT_ROOT/scripts/check-frontend-version.sh"; then
        echo ""
        echo "Commit blocked. Please rebuild the frontend before committing."
        echo "Run: cd frontend && npm run build"
        exit 1
    fi
fi

exit 0
