#!/usr/bin/env bash
# Pre-commit hook: ruff lint + format check + projection registry consistency.
#
# Install:  git config core.hooksPath .githooks
# Skip:     git commit --no-verify  (use sparingly)

set -euo pipefail

# Collect staged .py files (excludes deleted files)
STAGED=$(git diff --cached --name-only --diff-filter=d -- '*.py')
if [ -z "$STAGED" ]; then
    exit 0
fi

echo "pre-commit: ruff check (lint)"
if ! uv run ruff check $STAGED; then
    echo ""
    echo "Lint errors found. Run 'uv run ruff check --fix' to auto-fix."
    exit 1
fi

echo "pre-commit: ruff format --check"
if ! uv run ruff format --check $STAGED; then
    echo ""
    echo "Format errors found. Run 'uv run ruff format' to auto-fix."
    exit 1
fi

echo "pre-commit: projection registry consistency (PROJ001-004)"
if ! uv run python scripts/check_projections.py --all; then
    echo ""
    echo "Projection registry inconsistency detected. See errors above."
    exit 1
fi

echo "pre-commit: mypy type check"
if ! uv run mypy src/vibeproj/; then
    echo ""
    echo "Type errors found. Fix the issues reported above."
    exit 1
fi

# GPU fused kernel tests — run if CuPy is available, skip gracefully otherwise
if uv run python -c "import cupy" 2>/dev/null; then
    echo "pre-commit: fused kernel tests (GPU detected)"
    if ! uv run pytest tests/test_fused_kernels.py tests/test_helmert.py -x -q; then
        echo ""
        echo "GPU kernel tests failed."
        exit 1
    fi
else
    echo "pre-commit: skipping GPU tests (CuPy not available)"
fi
