#!/usr/bin/env bash
# Pre-commit lint hook — runs the same checks as bin/lint.sh, scoped to the
# Python files you're actually committing (so it never blocks on unrelated
# pre-existing lint debt elsewhere in the tree).
#
# black + isort run over all staged .py files; flake8 + mypy run over staged
# source files only (excluding tests/), matching bin/lint.sh's scope.
#
# Enable:        git config core.hooksPath .githooks      (bin/setup.sh does this)
# Bypass once:   git commit --no-verify
# Auto-fix:      ./bin/lint.sh --fix
set -uo pipefail

cd "$(git rev-parse --show-toplevel)"

# Staged Python files (Added / Copied / Modified — ignore deletions).
ALL_PY=$(git diff --cached --name-only --diff-filter=ACM -- '*.py')
if [ -z "$ALL_PY" ]; then
  exit 0
fi
# flake8 + mypy scope: drop tests/ to match bin/lint.sh (and pyproject mypy exclude).
SRC_PY=$(echo "$ALL_PY" | grep -v '^tests/' || true)

GREEN='\033[0;32m'; RED='\033[0;31m'; BOLD='\033[1m'; NC='\033[0m'
FAILED=0
TMP="$(mktemp)"

# run <name> <files> <cmd...> — skips silently if no files in scope.
run() {
  local name="$1"; local files="$2"; shift 2
  [ -z "$files" ] && return 0
  # shellcheck disable=SC2086
  if "$@" $files >"$TMP" 2>&1; then
    echo -e "${GREEN}✓${NC} $name"
  else
    echo -e "${RED}✗ $name${NC}"
    cat "$TMP"
    FAILED=1
  fi
}

echo -e "${BOLD}pre-commit: linting staged Python files${NC}"
run "black"  "$ALL_PY" uv run black --check
run "isort"  "$ALL_PY" uv run isort --check-only
run "flake8" "$SRC_PY" uv run flake8
run "mypy"   "$SRC_PY" uv run --with mypy mypy

rm -f "$TMP"

if [ "$FAILED" -ne 0 ]; then
  echo ""
  echo -e "${RED}${BOLD}Commit blocked by lint checks.${NC}"
  echo "  Auto-fix formatting:  ./bin/lint.sh --fix"
  echo "  Bypass (not advised): git commit --no-verify"
  exit 1
fi

echo -e "${GREEN}${BOLD}All lint checks passed.${NC}"
exit 0
