#!/usr/bin/env bash
# Pre-push lint gate.
#
# Local edit hook (~/.claude/hooks/post-tool-use/run_lint.sh) no longer
# auto-strips unused imports (rule F401) so subagent multi-step edits
# don't get sabotaged mid-flight. Side effect: a genuinely-unused import
# can slip into a push. This hook runs `ruff check` strictly (no --fix)
# on src/ and tests/ to catch that before it hits the remote.
#
# Scope note (deviation from original spec): we currently --select only
# the unused-name family (F401 unused-import, F811 redefinition). The
# broader ruleset configured in pyproject.toml ([E, F, W, I]) has ~100
# pre-existing violations across the tree — flipping it on wholesale
# would block every push. Tighten the --select set once those are
# triaged. The stated F401-slip-through risk is fully covered here.
#
# Install once per clone with:  scripts/install-pre-push-hook.sh
# Skip in true emergencies with: git push --no-verify
set -euo pipefail

# Run from repo root.
cd "$(git rev-parse --show-toplevel)"

# Locate ruff. Search order matches the venvs the SciTeX harness
# typically installs into; falls back to whatever ruff is on PATH.
# Operator-overridable via $SAC_PRE_PUSH_RUFF if a non-standard venv
# is in use (rare).
RUFF=""
for candidate in \
    "${SAC_PRE_PUSH_RUFF:-}" \
    ".venv/bin/ruff" \
    "/opt/venv-agent/bin/ruff" \
    "/opt/venv-sac/bin/ruff" \
    "$HOME/.local/bin/ruff" \
; do
  if [ -n "$candidate" ] && [ -x "$candidate" ]; then
    RUFF="$candidate"
    break
  fi
done
if [ -z "$RUFF" ] && command -v ruff >/dev/null 2>&1; then
  RUFF="$(command -v ruff)"
fi

if [ -z "$RUFF" ]; then
  # Loud failure — never silently skip the gate (handoff Q3). If a
  # genuine emergency requires bypass, --no-verify is documented as
  # the explicit override and shows up in the audit log.
  echo "PRE-PUSH BLOCKED: ruff binary not found." >&2
  echo "  Searched: \$SAC_PRE_PUSH_RUFF, .venv/bin/ruff, /opt/venv-agent/bin/ruff," >&2
  echo "           /opt/venv-sac/bin/ruff, \$HOME/.local/bin/ruff, PATH." >&2
  echo "  Install ruff via: pip install -e .[dev]" >&2
  echo "  Or point the hook at an existing ruff: export SAC_PRE_PUSH_RUFF=/path/to/ruff" >&2
  echo "  Or bypass once (emergency only): git push --no-verify" >&2
  exit 1
fi

# Strict check (no autofix). Narrow --select keeps the gate focused on
# the unused-import slip-through that motivated this hook.
# --extend-per-file-ignores excludes __init__.py re-export shims (the
# standard idiom — imports there *are* the public surface, not dead code).
if ! "$RUFF" check \
      --select F401,F811 \
      --extend-per-file-ignores "**/__init__.py:F401" \
      src/ tests/; then
  echo "" >&2
  echo "PRE-PUSH BLOCKED: ruff found unused-import / redefinition errors." >&2
  echo "Fix with:" >&2
  echo "  $RUFF check --select F401,F811 --extend-per-file-ignores '**/__init__.py:F401' --fix src/ tests/" >&2
  echo "Or skip the hook (only when truly needed) with --no-verify." >&2
  exit 1
fi
