#!/usr/bin/env bash
# pre-push hook — runs the EXACT same lint + test commands as GitHub Actions CI.
# Catches failures BEFORE CI, not after.
#
# To install: cp scripts/hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push
#
# CI equivalence:
#   Lint:  .github/workflows/ci.yml → lint job → ruff check src/ tests/ conftest.py --select E,F,W --ignore E501
#   Tests: .github/workflows/ci.yml → unit-tests job → pytest -n auto (same selection, same addopts)
#
# Layer 0 discipline (per docs/working/ci-hygiene-plan-2026-04-28.md):
#   - Warns when origin/main's last CI (code) run was a failure. Only the CI
#     workflow (ci.yml) gates a push; non-code workflows (Public Mirror,
#     Issue Snapshot, Memory Benchmarks, Publish) never mark main red for code.
#   - Refuses to push onto red main without an explicit override-reason.
#
# Override-reason mechanism (2026-06-01):
#   When main is red, every commit being pushed MUST carry a `Bypass-Reason:`
#   trailer. The path to get that trailer in is to commit with the env var
#   AXI_OVERRIDE_REASON="why" set — the commit-msg hook stamps the trailer.
#   This hook will, as a last-resort convenience, amend the trailer onto HEAD
#   if AXI_OVERRIDE_REASON is set at push time AND only HEAD is missing the
#   trailer. Every red-main push is logged to ~/.axi/pre-push-bypass.log.
#
#   `git push --no-verify` still skips this hook (Git can't prevent that
#   locally). Server-side branch protection is the second line of defense
#   and is tracked separately.

set -euo pipefail

# Everything below runs inside a function, and the last line both calls it
# and exits.
#
# Worktrees share one hooks directory, so `cp scripts/hooks/pre-push
# .git/hooks/` lands underneath anyone's in-flight push. Bash reads a script
# incrementally by byte offset, so an overwrite mid-run shifts those offsets
# and the interpreter resumes parsing mid-token — which cost a full 12-minute
# suite run on 2026-09-07: all 12,877 tests passed, the hook printed its
# success line, then died with `syntax error near unexpected token '('`.
#
# Bash parses a complete function definition before executing any of it, so
# the body is immune once read. Calling and exiting on ONE line closes the
# rest of the hole: without the `exit`, bash returns to reading the file and
# executes whatever trailing bytes the replacement left at that offset.
main() {

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

# Activate venv if not already active
if [ -z "${VIRTUAL_ENV:-}" ]; then
  if [ -f "$REPO_ROOT/../.venv/bin/activate" ]; then
    # shellcheck disable=SC1091
    source "$REPO_ROOT/../.venv/bin/activate"
  elif [ -f "$REPO_ROOT/.venv/bin/activate" ]; then
    source "$REPO_ROOT/.venv/bin/activate"
  fi
fi

# ── the interpreter ────────────────────────────────────────────────────
#
# Resolved explicitly, by path, rather than trusting `python` to be on PATH.
#
# Sourcing the venv's activate above sets VIRTUAL_ENV but has been observed
# NOT to prepend its bin to PATH under `set -euo pipefail`. On a machine with
# no `python` (macOS ships only `python3`) every check written as `python …`
# then exits 127 — and this hook read that as the check FAILING. A push was
# refused with "ADR number collision detected" on a branch that touches no
# ADR, and the test sweep never ran at all. That is why this gate has a
# reputation for being red for environmental reasons. The same applies to
# `ruff` and `pytest`, which live in the venv's bin and are run as modules
# through $PY_BIN below for exactly this reason.
PY_BIN=""
for _cand in \
    "${VIRTUAL_ENV:-}/bin/python" \
    "$REPO_ROOT/../.venv/bin/python" \
    "$REPO_ROOT/.venv/bin/python" \
    "$(command -v python3 2>/dev/null || true)" \
    "$(command -v python 2>/dev/null || true)"; do
  if [ -n "$_cand" ] && [ -x "$_cand" ]; then PY_BIN="$_cand"; break; fi
done
if [ -z "$PY_BIN" ]; then
  echo "✗ pre-push: no Python interpreter found — the checks cannot run."
  echo "  Looked for: \$VIRTUAL_ENV/bin/python, ../.venv/bin/python,"
  echo "              ./.venv/bin/python, python3, python"
  echo "  A gate that cannot run must not pass silently, so this blocks."
  exit 1
fi

# ── helpers ────────────────────────────────────────────────────────────
AXI_LOG_DIR="${HOME}/.axi"
AXI_BYPASS_LOG="${AXI_LOG_DIR}/pre-push-bypass.log"

log_bypass() {
  # log_bypass <branch> <sha> <reason-or-no-reason>
  mkdir -p "$AXI_LOG_DIR" 2>/dev/null || return 0
  local ts user
  ts="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  user="$(git config user.email 2>/dev/null || echo unknown)"
  printf '%s\tbranch=%s\tsha=%s\tuser=%s\treason=%s\n' \
    "$ts" "$1" "$2" "$user" "$3" >> "$AXI_BYPASS_LOG" 2>/dev/null || true
}

commit_has_bypass_trailer() {
  # commit_has_bypass_trailer <sha>
  git log -1 --format=%B "$1" 2>/dev/null \
    | git interpret-trailers --parse 2>/dev/null \
    | grep -qiE '^Bypass-Reason:[[:space:]]*[^[:space:]]'
}

# ── determine refs being pushed (stdin from git) ───────────────────────
# Format per githooks(5): <local-ref> <local-sha> <remote-ref> <remote-sha>
PUSH_INPUT="$(cat || true)"
CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
HEAD_SHA="$(git rev-parse HEAD)"

# ── CI status check on origin/main — Layer 0 discipline ────────────────
MAIN_RED=0
if command -v gh >/dev/null 2>&1; then
  echo "▶ pre-push: checking origin/main CI status..."
  # Only the CI (code) workflow gates a push. A red run of a non-code workflow
  # — Public Mirror (GitHub->GitLab), Issue Snapshot, Memory Benchmarks, Publish
  # — is not a broken tree and must not force a Bypass-Reason on every push.
  # Filter to ci.yml so those never count. (--limit 1 keeps the original quick-
  # heuristic semantics: an in-progress latest CI run reads as not-red.)
  last_status=$(gh run list --branch main --workflow ci.yml --limit 1 --json conclusion --jq '.[0].conclusion' 2>/dev/null || echo "unknown")
  if [ "$last_status" = "failure" ]; then
    MAIN_RED=1
    echo ""
    echo "⚠ pre-push: origin/main is RED (last CI run failed)."
    echo "   View: gh run list --branch main --workflow ci.yml --limit 5"
    echo ""
    echo "   Per ci-hygiene-plan-2026-04-28.md Rule 1: never push onto red main."
    echo "   Fix or revert is the next commit, not a new feature."
    echo ""
  elif [ "$last_status" = "success" ]; then
    echo "✓ pre-push: origin/main is GREEN"
  else
    echo "  (origin/main status: ${last_status} — proceeding)"
  fi
fi

# ── Override-reason enforcement when main is red ───────────────────────
if [ "$MAIN_RED" = "1" ]; then
  # Gather commits being pushed. If push stdin is empty (rare — direct hook
  # invocation), fall back to HEAD only.
  commits_to_check=""
  if [ -n "$PUSH_INPUT" ]; then
    while read -r local_ref local_sha remote_ref remote_sha; do
      [ -z "$local_sha" ] && continue
      # Zero sha means deletion; skip.
      case "$local_sha" in
        0000000000000000000000000000000000000000) continue ;;
      esac
      if [ "$remote_sha" = "0000000000000000000000000000000000000000" ] || [ -z "$remote_sha" ]; then
        # New branch — walk only commits not already on any remote ref.
        range_commits="$(git rev-list --max-count=50 "$local_sha" --not --remotes 2>/dev/null || true)"
      else
        range_commits="$(git rev-list "${remote_sha}..${local_sha}" 2>/dev/null || true)"
      fi
      commits_to_check="${commits_to_check}${range_commits}
"
    done <<< "$PUSH_INPUT"
  fi
  if [ -z "${commits_to_check//[[:space:]]/}" ]; then
    commits_to_check="$HEAD_SHA"
  fi

  missing=""
  while IFS= read -r sha; do
    [ -z "$sha" ] && continue
    if ! commit_has_bypass_trailer "$sha"; then
      missing="${missing}${sha}\n"
    fi
  done <<< "$commits_to_check"

  if [ -n "$missing" ]; then
    if [ -n "${AXI_OVERRIDE_REASON:-}" ]; then
      # Convenience path: if ONLY HEAD is missing the trailer, amend it in.
      missing_count=$(printf '%b' "$missing" | grep -c . || true)
      if [ "$missing_count" = "1" ] && printf '%b' "$missing" | grep -q "^${HEAD_SHA}$"; then
        echo "▶ pre-push: stamping Bypass-Reason trailer onto HEAD from AXI_OVERRIDE_REASON"
        git commit --amend --no-edit \
          --trailer "Bypass-Reason: ${AXI_OVERRIDE_REASON}" >/dev/null
        HEAD_SHA="$(git rev-parse HEAD)"
        echo "  ✓ trailer stamped (new HEAD: ${HEAD_SHA})"
        echo "  ⚠ HEAD rewritten — you may need to force-push if the old sha was already pushed."
        log_bypass "$CURRENT_BRANCH" "$HEAD_SHA" "$AXI_OVERRIDE_REASON"
      else
        echo "✗ pre-push: main is RED and ${missing_count} commit(s) lack a Bypass-Reason: trailer:"
        printf '%b' "$missing" | sed 's/^/    /'
        echo ""
        echo "   AXI_OVERRIDE_REASON is set but more than just HEAD is missing the trailer."
        echo "   Either:"
        echo "     (a) wait for main to go green, or"
        echo "     (b) re-author the listed commits with AXI_OVERRIDE_REASON=\"why\" set so"
        echo "         the commit-msg hook stamps a Bypass-Reason trailer on each."
        log_bypass "$CURRENT_BRANCH" "$HEAD_SHA" "refused-multi-commit-no-trailer"
        exit 1
      fi
    else
      echo "✗ pre-push: main is RED and the following commit(s) lack a Bypass-Reason: trailer:"
      printf '%b' "$missing" | sed 's/^/    /'
      echo ""
      echo "   Per ci-hygiene-plan-2026-04-28.md Rule 1: never push onto red main without a receipt."
      echo ""
      echo "   To proceed, either:"
      echo "     (a) wait for main to go green, or"
      echo "     (b) re-commit with AXI_OVERRIDE_REASON=\"why this push is necessary\""
      echo "         set in the environment — the commit-msg hook will stamp the trailer."
      echo ""
      echo "   To stamp the trailer on HEAD only at push time, re-run this push with"
      echo "   AXI_OVERRIDE_REASON=\"...\" set; the hook will amend HEAD for you."
      echo ""
      echo "   Note: 'git push --no-verify' skips this hook entirely. Every --no-verify"
      echo "   push onto red main is an audit event. Server-side branch protection is"
      echo "   the binding enforcement; this hook is the courtesy stop."
      log_bypass "$CURRENT_BRANCH" "$HEAD_SHA" "refused-no-trailer"
      exit 1
    fi
  else
    echo "✓ pre-push: all commits being pushed carry a Bypass-Reason trailer"
    log_bypass "$CURRENT_BRANCH" "$HEAD_SHA" "trailer-present"
  fi
fi

# Skip CI-equivalent checks in test mode (smoke tests just exercise the
# override-reason gate).
if [ "${AXI_PRE_PUSH_SKIP_CHECKS:-0}" = "1" ]; then
  echo "  (AXI_PRE_PUSH_SKIP_CHECKS=1 — skipping lint/tests)"
  exit 0
fi

# ── Hook freshness ──────────────────────────────────────────────────────
# This hook is a COPY of scripts/hooks/pre-push. `make install` used to copy it
# only when absent, so an improved hook silently never reached anyone who had
# installed once — the hook drifting from its source is the same silent-drift
# class as the artifacts below.
#
# WARN, never block. Gating a push on the gate's own version would be a false
# failure, and this hook legitimately differs from its source on any branch that
# is changing it — including the one that introduced this check.
_hook_src="scripts/hooks/pre-push"
if [ -f "$_hook_src" ] && [ -f "$0" ] && ! cmp -s "$_hook_src" "$0"; then
  echo "⚠ pre-push: installed hook differs from $_hook_src — run: make hooks"
fi

# ── Stale build artifacts ───────────────────────────────────────────────
# Switching between a branch that has a builtin extension and one that does not
# leaves the extension's TRACKED files removed but its __pycache__ behind — so
# the directory still exists on disk with no axiom-extension.toml, and
# test_all_builtins_have_manifests correctly reports a half-installed builtin.
# That cost two full suite runs on 2026-08-19 before the cause was obvious.
#
# Scoped deliberately: __pycache__ is always regenerable, and a directory that
# is empty afterwards contained nothing tracked and nothing of yours. This is
# NOT `git clean -fdx` — that would delete untracked work in progress, which a
# hook has no business doing.
echo "▶ pre-push: clearing stale build artifacts..."
find src tests -type d -name __pycache__ -prune -exec rm -rf {} + 2>/dev/null || true
find src/axiom/extensions/builtins -mindepth 1 -depth -type d -empty -delete 2>/dev/null || true
echo "✓ pre-push: artifacts clear"

# ── Repairs the lint job would fail for, applied before anything is sent ──
# AGENTS.md is the canon; the Cursor, Junie, Copilot and Gemini files are
# generated from it. Ruff's E/F/W findings have a --fix. Both used to print
# the command and stop, so the red run happened on GitHub instead of here.
# Git has already chosen the commits for this push, so a commit made now
# would not be in it. The repair is committed and the push stops. The next
# push sends the repair. A dirty tree is left alone: the hook will not stage
# someone else's uncommitted work.
echo "▶ pre-push: context files and ruff, repairing when the tree is clean..."
_dirty="$(git status --porcelain)"
_repaired=0
if ! PYTHONPATH=src "$PY_BIN" -m axiom.extensions.builtins.context.cli check >/dev/null 2>&1; then
  if [ -n "$_dirty" ]; then
    echo "✗ pre-push: context files drifted from AGENTS.md — push blocked"
    echo "  The tree is dirty, so this was not committed for you."
    echo "  Run: PYTHONPATH=src $PY_BIN -m axiom.extensions.builtins.context.cli sync"
    exit 1
  fi
  echo "  context files drifted — syncing from AGENTS.md"
  PYTHONPATH=src "$PY_BIN" -m axiom.extensions.builtins.context.cli sync
  _repaired=1
fi
if ! "$PY_BIN" -m ruff check src/ tests/ conftest.py --select E,F,W --ignore E501; then
  if [ -n "$_dirty" ]; then
    echo "✗ pre-push: ruff found errors — push blocked"
    echo "  The tree is dirty, so --fix was not committed for you."
    echo "  Run: $PY_BIN -m ruff check src/ tests/ conftest.py --select E,F,W --ignore E501 --fix"
    exit 1
  fi
  echo "  ruff failed — applying --fix"
  "$PY_BIN" -m ruff check src/ tests/ conftest.py --select E,F,W --ignore E501 --fix || true
  if ! "$PY_BIN" -m ruff check src/ tests/ conftest.py --select E,F,W --ignore E501; then
    echo "✗ pre-push: ruff still fails after --fix — push blocked"
    exit 1
  fi
  _repaired=1
fi
if [ "$_repaired" = "1" ]; then
  git add -A -- .cursor/rules/axiom.mdc .junie/guidelines.md .github/copilot-instructions.md GEMINI.md CLAUDE.md
  git add -u -- src tests conftest.py
  if git diff --cached --quiet; then
    echo "✗ pre-push: the repair did not change a tracked file — push blocked"
    exit 1
  fi
  git commit -m "$(cat <<'EOF'
chore: apply the pre-push repair

Context files are generated from AGENTS.md, and ruff --fix is the repair
the lint job would otherwise fail for on GitHub. Nothing was pushed.
EOF
)"
  echo "✓ pre-push: repair committed. Nothing was sent. Run git push again."
  exit 1
fi
echo "✓ pre-push: context files in sync"
echo "✓ pre-push: ruff passed"

# These three fail in seconds and do not need a database. They used to be
# found at the end of the unit suite, after the throwaway database and the
# fifteen-minute run. A stray root directory or a customer name in the
# platform tree stops here.
echo "▶ pre-push: cheap guards, before the suite..."
if ! "$PY_BIN" -m pytest -q --tb=line \
  tests/test_repo_hygiene.py::TestRootDirPolicy::test_no_unexpected_root_dirs \
  tests/test_mirror.py::test_public_surface_has_no_forbidden_terms \
  tests/test_axiom_names_no_domain.py::TestNoModuleNamesACustomer::test_not_one
then
  echo "✗ pre-push: a cheap guard failed — push blocked before the suite"
  exit 1
fi
echo "✓ pre-push: cheap guards passed"

# ── ADR-number collision lint ───────────────────────────────────────────
echo "▶ pre-push: ADR number collision lint..."
if "$PY_BIN" scripts/lint_adr_numbers.py; then
  echo "✓ pre-push: ADR numbers unique"
else
  _rc=$?
  echo ""
  if [ "$_rc" -eq 127 ]; then
    # 127 is "could not run it", which is not a verdict about ADR numbers.
    echo "✗ pre-push: could not RUN the ADR lint ($PY_BIN, exit 127) — push blocked"
    echo "  This is not a collision; the linter never executed."
  else
    echo "✗ pre-push: ADR number collision detected — push blocked"
    echo "  Pick the next free number with: $PY_BIN scripts/lint_adr_numbers.py --next"
  fi
  exit 1
fi

# ── A throwaway database for the tests (matches CI, which gives the suite an EMPTY Postgres) ──────
# The root conftest points an unchosen database at an address that refuses connections, so a test can
# never reach a developer's live data. That makes the database tests fail without a server, so the hook
# makes its own: a NEW, empty `axiom_hook_*` database on the reachable server, dropped on any exit.
# Nothing existing on that server is touched (scripts/hooks/throwaway_postgres.py; tests/infra covers it).
HOOK_DB_URL=""
hook_db_cleanup() {
  if [ -n "$HOOK_DB_URL" ]; then
    "$PY_BIN" scripts/hooks/throwaway_postgres.py drop "$HOOK_DB_URL" >/dev/null 2>&1 || true
    HOOK_DB_URL=""
  fi
}
if [ -n "${AXI_HOOK_NO_POSTGRES_REASON:-}" ]; then
  # The one documented exception: no server is reachable AND you say why. It is logged like a red-main
  # bypass, and the database tests will fail, which is the point of making it loud.
  echo "⚠ pre-push: running WITHOUT a throwaway database: ${AXI_HOOK_NO_POSTGRES_REASON}"
  log_bypass "$CURRENT_BRANCH" "$HEAD_SHA" "no-postgres: ${AXI_HOOK_NO_POSTGRES_REASON}"
else
  echo "▶ pre-push: creating a throwaway test database..."
  if ! HOOK_DB_URL="$(PYTHONPATH=src "$PY_BIN" scripts/hooks/throwaway_postgres.py create)"; then
    HOOK_DB_URL=""
    echo "✗ pre-push: could not create a throwaway database — push blocked"
    exit 1
  fi
  trap hook_db_cleanup EXIT INT TERM
  export AXIOM_DB_URL="$HOOK_DB_URL"
  echo "✓ pre-push: throwaway database ready (dropped when the hook ends)"
fi

# ── Test suite (matches CI unit-tests job — both testpaths) ────────────
# CI uses pyproject.toml's testpaths: ["tests", "src/axiom/extensions/builtins"].
echo "▶ pre-push: running test suite (unit only, no integration)..."

# Deliberately no -m: pyproject's addopts already excludes integration,
# federation_lifecycle, install_path and classroom_e2e, and passing -m here
# OVERRIDES that whole expression rather than adding to it. The hook was
# therefore running three categories CI never runs — including install_path,
# which wants Docker and network on a laptop. CI's unit job is
# `pytest -n auto -v --tb=short`; this matches its selection. Testpaths come
# from pyproject too.
#
# Parallel on the throwaway database. The old comment here said "serial on purpose": workers
# collided on schemas left in the developer's LIVE database (`relation "verdicts" does not exist`).
# On a fresh empty database each worker gets its own schema suffix and the collision cannot happen:
# the same suite is 15-25 minutes parallel against 50+ serial. AXI_HOOK_WORKERS=0 forces serial.
HOOK_WORKERS="${AXI_HOOK_WORKERS:-4}"
# The laptop holds the blast-radius map (.testmondata). A later push runs
# only the tests that executed the lines this commit changed. AXI_HOOK_FULL=1
# runs every test, which is what main still does. testmon does not share
# workers with xdist, so the selected run is one process.
PYTEST_ARGS=(--tb=short -q --no-header --timeout=90)
if [ "${AXI_HOOK_FULL:-0}" = "1" ] || ! "$PY_BIN" -c "import testmon" >/dev/null 2>&1; then
  echo "▶ pre-push: running the full unit suite"
  PYTEST_ARGS+=(-n "$HOOK_WORKERS")
else
  echo "▶ pre-push: running the tests this change can affect (AXI_HOOK_FULL=1 runs them all)"
  PYTEST_ARGS+=(--testmon)
fi
if "$PY_BIN" -m pytest "${PYTEST_ARGS[@]}" 2>&1; then
  echo "✓ pre-push: all tests passed"
else
  echo ""
  echo "✗ pre-push: tests failed — push blocked"
  echo "  Fix the failures above, or use --no-verify to bypass"
  exit 1
fi
}

main "$@"; exit $?
