#!/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.
# One sweep at a time on this machine, across every worktree and session. Two
# parallel full runs took a Mac to load 71 and failed both. A holder that died
# leaves its pid behind, and the next hook takes over.
HOOK_LOCK_DIR="${AXI_HOOK_LOCK_DIR:-$HOME/.axi/locks}/pre-push-sweep"
hook_lock_acquire() {
  local waited=0 limit="${AXI_HOOK_LOCK_WAIT:-5400}" holder said=""
  mkdir -p "$(dirname "$HOOK_LOCK_DIR")"
  while ! mkdir "$HOOK_LOCK_DIR" 2>/dev/null; do
    holder="$(cat "$HOOK_LOCK_DIR/pid" 2>/dev/null || true)"
    if [ -n "$holder" ] && ! kill -0 "$holder" 2>/dev/null; then
      rm -f "$HOOK_LOCK_DIR/pid"; rmdir "$HOOK_LOCK_DIR" 2>/dev/null || true
      continue
    fi
    if [ "$waited" -ge "$limit" ]; then
      echo "✗ pre-push: another test sweep (pid ${holder:-unknown}) held the machine for ${limit}s"
      echo "  Check that process, then push again."
      return 1
    fi
    if [ -z "$said" ]; then
      echo "▶ pre-push: waiting for another test sweep to finish (pid ${holder:-unknown})"
      said=1
    fi
    sleep "${AXI_HOOK_LOCK_POLL:-10}"; waited=$((waited + ${AXI_HOOK_LOCK_POLL:-10}))
  done
  echo "$$" >"$HOOK_LOCK_DIR/pid"
}
hook_lock_release() {
  if [ "$(cat "$HOOK_LOCK_DIR/pid" 2>/dev/null)" = "$$" ]; then
    rm -f "$HOOK_LOCK_DIR/pid"; rmdir "$HOOK_LOCK_DIR" 2>/dev/null || true
  fi
}
# end hook lock

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 is judged by its CURRENT HEAD, never by "the last completed run". The
# main concurrency group replaces the pending run on every merge, so after a
# burst the newest completed run describes an older head (#1782): a stale red
# blocked pushes for an hour on 2026-11-10, and a stale green would hide a head
# nobody tested. `release ci-head` reads the run for the head itself and says
# one of: success, failure (with the failing checks), pending, or superseded
# (no run of its own; the newest completed head is named). Only a failure on
# the head is red. When the skill cannot answer (module missing, forge
# unreadable) the hook falls back to the old last-run heuristic below.
MAIN_RED=0
if command -v gh >/dev/null 2>&1; then
  echo "▶ pre-push: checking origin/main CI status..."
  _slug="$(gh repo view --json nameWithOwner --jq .nameWithOwner 2>/dev/null || true)"
  _head_json=""
  if [ -n "$_slug" ]; then
    _head_json="$(PYTHONPATH=src "$PY_BIN" -m axiom.extensions.builtins.release.cli ci-head \
      --repo "$_slug" --format json 2>/dev/null || true)"
  fi
  _verdict=""
  _line=""
  if [ -n "$_head_json" ]; then
    _verdict="$(printf '%s' "$_head_json" | "$PY_BIN" -c \
      'import json,sys
try:
    print(json.load(sys.stdin).get("verdict", ""))
except Exception:
    pass' 2>/dev/null || true)"
    _line="$(printf '%s' "$_head_json" | "$PY_BIN" -c \
      'import json,sys
try:
    print(json.load(sys.stdin).get("line", ""))
except Exception:
    pass' 2>/dev/null || true)"
  fi
  if [ -n "$_verdict" ] && [ "$_verdict" != "unknown" ]; then
    case "$_verdict" in
      failure)
        MAIN_RED=1
        echo ""
        echo "⚠ pre-push: origin/main is RED on its current head."
        echo "   $_line"
        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 ""
        ;;
      success)
        echo "✓ pre-push: origin/main is GREEN on its current head"
        ;;
      superseded|pending)
        # Untested or still running is not red: a stale failure on an older
        # head does not block this push, and a real one on the head would have.
        echo "  (origin/main: $_line — proceeding)"
        ;;
      *)
        echo "  (origin/main: ${_verdict} — proceeding)"
        ;;
    esac
  else
    # Fallback: the pre-#1782 heuristic. Only the CI (code) workflow gates a
    # push. A red run of a non-code workflow (Public Mirror, Issue Snapshot,
    # Memory Benchmarks, Publish) is not a broken tree and must not force a
    # Bypass-Reason on every push, so this filters to ci.yml. An in-progress
    # latest 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; the head verdict was unavailable)."
      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 (last completed run; the head verdict was unavailable)"
    else
      echo "  (origin/main status: ${last_status} — proceeding)"
    fi
  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}"
_blast() { "$PY_BIN" scripts/testmon_blast_radius.py "$@"; }
_base="$(git merge-base origin/main HEAD 2>/dev/null || true)"

# The same rule CI uses to skip the unit suite, so a documentation push does not
# wait on tests that cannot see it. The tests that do read docs still run.
if [ "${AXI_HOOK_FULL:-0}" != "1" ] && [ -n "$_base" ] \
  && git diff --name-only "$_base" HEAD | _blast --docs-only; then
  echo "▶ pre-push: documentation only, running the document checks"
  if "$PY_BIN" -m pytest --tb=short -q --no-header --timeout=90 -n 0 \
    tests/test_adr_numbering.py tests/test_lint_adr_numbers.py tests/test_repo_hygiene.py \
    tests/test_axiom_names_no_domain.py 2>&1; then
    echo "✓ pre-push: document checks passed"
    return 0
  fi
  echo "✗ pre-push: document checks failed — push blocked"
  exit 1
fi

# The laptop holds the blast-radius map (.testmondata). A new worktree copies the
# newest sibling's, because testmon compares content hashes and an older map is
# a diff. The choice is CI's: scripts/testmon_blast_radius.py runs every test when
# configuration or fixtures changed since the map's commit, or when the selection
# passes a third of the suite. addopts carries -m, which turns plain --testmon's
# selection off, so --testmon-forceselect is required. AXI_HOOK_FULL=1 runs every
# test, which is what main still does. See docs/specs/spec-cicd-and-deployment.md.
PYTEST_ARGS=(--tb=short -q --no-header --timeout=90)
_mode=full
_n=""
if [ "${AXI_HOOK_FULL:-0}" = "1" ]; then
  echo "testmon decision: full suite: AXI_HOOK_FULL=1"
elif ! "$PY_BIN" -c "import testmon" >/dev/null 2>&1; then
  echo "testmon decision: full suite: pytest-testmon is not installed"
else
  _blast --seed || true
  _map_commit="$(_blast --map-commit 2>/dev/null || true)"
  if [ -f .testmondata ] && [ -n "$_map_commit" ]; then
    _blast --align .testmondata >/dev/null
    _changed="$(mktemp)"
    _changed_args=()
    if git diff --name-only "$_map_commit" HEAD >"$_changed" 2>/dev/null; then
      _changed_args=(--changed-files "$_changed")
    fi
    _collect_rc=0
    _collect="$("$PY_BIN" -m pytest --testmon --testmon-forceselect --collect-only --tb=no 2>&1)" \
      || _collect_rc=$?
    if [ "$_collect_rc" -eq 0 ] || [ "$_collect_rc" -eq 5 ]; then
      _decision="$(printf '%s\n' "$_collect" | _blast --decide --map-key "testmon-local-$_map_commit" \
        ${_changed_args[@]+"${_changed_args[@]}"} || true)"
    else
      _decision="$(_blast --decide --no-selection --map-key "testmon-local-$_map_commit" \
        ${_changed_args[@]+"${_changed_args[@]}"} || true)"
    fi
    rm -f "$_changed"
    printf '%s\n' "$_decision" | grep '^testmon decision:' || true
    _mode="$(printf '%s\n' "$_decision" | sed -n 's/^mode=//p')"
    _n="$(printf '%s\n' "$_decision" | sed -n 's/^n=//p')"
  else
    echo "testmon decision: full suite: no map here or in a sibling worktree"
  fi
fi

# A full sweep belongs to CI: it costs this machine 20 to 35 minutes and most of
# its disk, and the required checks run it anyway. When selection cannot narrow
# the run, the hook runs the test files this branch changed, and the push goes
# on. AXI_HOOK_FULL=1 still runs everything here.
_changed_tests=()
if [ "$_mode" != "blast" ] && [ "${AXI_HOOK_FULL:-0}" != "1" ]; then
  while IFS= read -r _f; do
    if [ -f "$_f" ]; then _changed_tests+=("$_f"); fi
  done < <(git diff --name-only --diff-filter=d origin/main...HEAD 2>/dev/null \
    | grep -E '(^|/)test_[^/]*\.py$' || true)
  # A change to the log's code also runs the logging end-to-end suite (#1818): the unit
  # tests prove each part, and only this suite proves they still compose.
  if git diff --name-only --diff-filter=d origin/main...HEAD 2>/dev/null \
      | grep -qE '^src/axiom/(attest|extensions/builtins/(attest|journal))/'; then
    _changed_tests+=("tests/logbook_e2e")
  fi
  if [ "${#_changed_tests[@]}" -eq 0 ]; then
    echo "✓ pre-push: no full sweep on this machine; CI runs the suite"
    return 0
  fi
  _mode=changed
fi
if [ "$_mode" = "changed" ]; then
  echo "▶ pre-push: running the ${#_changed_tests[@]} test files this branch changed; CI runs the full suite"
  PYTEST_ARGS+=(-n 0 "${_changed_tests[@]}")
elif [ "$_mode" = "blast" ]; then
  # Below about 32 tests, workers cost more than they save.
  _workers=0
  if [ -n "$_n" ] && [ "$_n" -ge 32 ]; then _workers="$HOOK_WORKERS"; fi
  echo "▶ pre-push: running the $_n tests this change can affect (AXI_HOOK_FULL=1 runs them all)"
  PYTEST_ARGS+=(-n "$_workers" --testmon --testmon-forceselect)
elif "$PY_BIN" -c "import testmon" >/dev/null 2>&1; then
  echo "▶ pre-push: running the full unit suite and refreshing the map"
  PYTEST_ARGS+=(-n "$HOOK_WORKERS" --testmon-noselect)
else
  echo "▶ pre-push: running the full unit suite"
  PYTEST_ARGS+=(-n "$HOOK_WORKERS")
fi
_rc=0
# A small selection runs beside a sweep; only runs with workers take turns.
_sweep=1
if [ "$_mode" = "blast" ] && [ "${_workers:-0}" -eq 0 ]; then _sweep=0; fi
if [ "$_mode" = "changed" ]; then _sweep=0; fi
if [ "$_sweep" -eq 1 ]; then hook_lock_acquire || exit 1; fi
"$PY_BIN" -m pytest "${PYTEST_ARGS[@]}" 2>&1 || _rc=$?
if [ "$_sweep" -eq 1 ]; then hook_lock_release; fi
# Exit 5 is an empty selection: nothing this change touches has a test.
if [ "$_rc" -eq 0 ] || { [ "$_rc" -eq 5 ] && [ "$_mode" != "full" ]; }; then
  git rev-parse HEAD >.testmondata.commit 2>/dev/null || true
  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 $?
