#!/usr/bin/env bash
# Pre-commit hook: ruff check + format before every commit.
# Activate: git config core.hooksPath .githooks
#
# Runs only on staged Python files for speed.
# Full checks (mypy, pytest) are CI-only.

set -euo pipefail

# --- Stage 0: Block gitignored files ---
STAGED=$(git diff --cached --name-only)
if [ -n "$STAGED" ]; then
    IGNORED=$(echo "$STAGED" | git check-ignore --no-index --stdin || true)
    if [ -n "$IGNORED" ]; then
        echo ""
        echo "BLOCKED: gitignored files are staged:"
        echo "$IGNORED"
        echo "  Remove with: git reset HEAD <file>"
        exit 1
    fi
fi

STAGED_PY=$(git diff --cached --name-only --diff-filter=ACM -- '*.py' || true)

if [ -z "$STAGED_PY" ]; then
    exit 0
fi

echo "pre-commit: ruff check (staged .py files)..."
if ! uv run ruff check $STAGED_PY; then
    echo ""
    echo "BLOCKED: ruff check failed. Fix lint errors before committing."
    echo "  Auto-fix:  uv run ruff check --fix ."
    exit 1
fi

echo "pre-commit: ruff format --check (staged .py files)..."
if ! uv run ruff format --check $STAGED_PY; then
    echo ""
    echo "BLOCKED: ruff format failed. Fix formatting before committing."
    echo "  Auto-fix:  uv run ruff format ."
    exit 1
fi

echo "pre-commit: all checks passed."
