#!/usr/bin/env sh
#
# pre-push: run the gates that the CHANGED FILES can affect, and nothing else.
#
# WHY NOT `pnpm run verify` — THE WHOLE BUNDLE — ON EVERY PUSH
#
# It used to. The bundle is fifteen steps (format, three register checks, tsc,
# eslint, design, desktop, unit, home, five gate tests), and CI runs exactly the
# same fifteen on every PR — this hook's own banner said "same bundle as CI".
# Locally it ran on a 4-core laptop hosting five to twenty agent sessions at
# once. On 2026-09-11 one push sat in this hook for SEVEN HOURS THIRTEEN MINUTES
# at load 16.65 before it was killed — for a commit that touched four shell
# scripts and no TypeScript at all. That is not a slow gate; that is a gate that
# has stopped being one, because the only way through it was --no-verify.
#
# The definition of "verified" is CI calling `verify` verbatim. This hook is a
# preview of that, and a preview that costs more than the thing it previews is
# worth nothing. So:
#
#   1. Only run what the diff can break. Shell scripts cannot fail tsc.
#   2. A hard watchdog. Fifteen minutes, then a loud exit that names CI as the
#      gate and says how to proceed — instead of silence until someone notices.
#   3. Print the load up front, so "slow" has a visible cause.
#
# Everything below the scoped gates — schema, smoke, prod dogfood — is unchanged.
set -e

# ── branch deletion only? nothing to check ────────────────────────────────────
_saw_ref=""; _has_commits=""
while read -r _lref _lsha _rref _rsha; do
  _saw_ref=1
  case "$_lsha" in *[!0]*) _has_commits=1 ;; esac
done
if [ -n "$_saw_ref" ] && [ -z "$_has_commits" ]; then
  echo "→ pre-push: branch deletion only — skipping checks"
  exit 0
fi

# ── stale install? that is not your change, fix it first ─────────────────────
if [ pnpm-lock.yaml -nt node_modules/.modules.yaml ] 2>/dev/null; then
  echo "✗ node_modules is older than pnpm-lock.yaml."
  echo "  This is an INSTALL problem, not a problem with your change — and left"
  echo "  alone it surfaces as bogus 'Cannot find module' type errors."
  echo "  Run: pnpm install"
  exit 1
fi

# ── watchdog: no hook runs for hours ─────────────────────────────────────────
# A background timer that kills THIS shell. Not `timeout(1)` around each step:
# the failure we saw was the SUM of steps under load, not one step hanging.
_LIMIT=900
# The sleep holds none of the caller's descriptors: the trap below stops this
# subshell, not the sleep under it, and an orphaned sleep that still held the
# caller's pipe kept `git push | tail` (or any tool that waits for the output
# to close) open for the full limit after the push had landed (2026-11-12).
(
  sleep "$_LIMIT" </dev/null >/dev/null 2>&1
  echo ""
  echo "✗ pre-push exceeded $((_LIMIT / 60)) minutes (load $(cut -d' ' -f1 /proc/loadavg 2>/dev/null) on $(nproc 2>/dev/null) cores)."
  echo "  This hook previews the CI bundle; CI runs the identical bundle on the PR."
  echo "  On an oversubscribed box the preview is the bottleneck, not the check."
  echo "  Push with:  git push --no-verify   — and let CI be the gate it already is."
  kill -TERM "$$" 2>/dev/null
) &
_watchdog=$!

# ── what changed? ─────────────────────────────────────────────────────────────
_def=$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's|^origin/||')
[ -z "$_def" ] && for _c in main master; do
  git rev-parse --verify --quiet "refs/remotes/origin/$_c" >/dev/null 2>&1 && { _def="$_c"; break; }
done
_base=$(git merge-base HEAD "origin/${_def:-main}" 2>/dev/null || echo "")

_changed=$(mktemp)
trap 'pkill -P "$_watchdog" 2>/dev/null || :; kill "$_watchdog" 2>/dev/null || :; rm -f "$_changed"' EXIT
if [ -n "$_base" ]; then
  git diff --name-only "$_base"...HEAD > "$_changed" 2>/dev/null
else
  git ls-files > "$_changed"   # no base to diff against — treat everything as changed
fi

# Read from the FILE, never `printf | grep -q`: under pipefail that construct
# reports failure on a successful match once the payload passes the pipe buffer
# (fleet SHARED.md, "Central audits"). This hook has no pipefail, but the habit
# is cheaper than the incident.
touches() { grep -qE "$1" "$_changed"; }

# Route each path to the suite that actually COVERS it.
#
# `scripts/test/` used to sit in the _ops arm, and that was backwards in both
# directions. test:ops runs `scripts/hetzner/test-*.sh` and nothing else — no
# file under scripts/test/ can affect it. Meanwhile scripts/test/ holds the 218
# .ts files that ARE the unit suite (scripts/test-unit.ts globs the directory),
# and the unit suite lives in the _app arm. So editing a unit test ran an
# unrelated shell suite and never ran the unit suite it belonged to: a broken
# test added under scripts/test/ passed pre-push.
#
# The .sh gate scripts that also live there (deploy-ref-gate, not-behind-gate,
# client-ledger-gate, deploy-ready-gate) belong to the _register arm, which is
# what runs them.
_app=""; _ops=""; _register=""
touches '^(src|home|widget|extension)/|^scripts/test/.*\.ts$|^(package\.json|pnpm-lock\.yaml|tsconfig.*\.json|eslint\.config\.[cm]?js|next\.config\.[cm]?js)$' && _app=1
touches '^scripts/(hetzner|site-template)/' && _ops=1
touches '^scripts/hetzner/apps\.conf$|^scripts/ci/|^scripts/test/.*gate\.sh$|^docs/telegram-notifications\.md$' && _register=1

echo "→ pre-push: $(wc -l < "$_changed") file(s) vs origin/${_def:-main} — app:${_app:-0} ops:${_ops:-0} register:${_register:-0} — load $(cut -d' ' -f1 /proc/loadavg 2>/dev/null) on $(nproc 2>/dev/null) cores"

# ── always: format, but only the files you touched ───────────────────────────
# `prettier --check .` walks the whole repo and took minutes under load; the
# files in the diff take seconds and are the only ones you can have broken.
_fmt=$(grep -E '\.(ts|tsx|js|mjs|cjs|json|md|yml|yaml|css)$' "$_changed" | while read -r f; do [ -f "$f" ] && printf '%s\n' "$f"; done)
if [ -n "$_fmt" ]; then
  echo "→ format:check ($(printf '%s\n' "$_fmt" | wc -l) changed file(s))"
  # shellcheck disable=SC2086
  pnpm exec prettier --check $_fmt
fi

# ── ops: shell scripts and the site template ─────────────────────────────────
if [ -n "$_ops" ]; then
  grep -E '\.sh$' "$_changed" | while read -r f; do
    [ -f "$f" ] && bash -n "$f"
  done
  echo "→ test:ops (scripts/ changed)"
  pnpm run test:ops
fi

# ── register: apps.conf and the CI checks that read it ───────────────────────
if [ -n "$_register" ]; then
  echo "→ register checks (apps.conf / scripts/ci changed)"
  pnpm run check:deploy-ready
  pnpm run check:client-ledger
  pnpm run check:telegram-registry
  pnpm run test:deploy-ref-gate
  pnpm run test:not-behind-gate
  pnpm run test:deploy-ready-gate
  pnpm run test:client-ledger-gate
fi

# ── app: TypeScript, lint, design, desktop, unit, home ───────────────────────
if [ -n "$_app" ]; then
  echo "→ app bundle (src/home/widget changed): tsc + lint + check:design + check:desktop + test:unit + test:home"
  tsc --noEmit
  pnpm run lint
  pnpm run check:design
  pnpm run check:desktop
  pnpm run test:unit
  pnpm run test:home
fi

if [ -z "$_app$_ops$_register" ]; then
  echo "→ no gated paths changed (docs/config only) — nothing to run locally; CI still runs the full bundle"
fi

# ── schema (unchanged) ───────────────────────────────────────────────────────
_touches_schema=""
if [ -n "$_base" ]; then
  git diff --name-only "$_base"...HEAD 2>/dev/null | grep -qE '^(src/db/schema/|drizzle/)' && _touches_schema=1
else
  _touches_schema=1   # cannot tell — treat as yours
fi
if [ -n "$_touches_schema" ]; then
  echo "→ check:schema (this branch changes schema — a mismatch is yours)"
  pnpm run check:schema
else
  echo "→ check:schema (branch touches no schema — mismatches are ambient, not blocking)"
  pnpm run check:schema || echo "  ⚠ schema mismatch predates this branch. Fix with: pnpm run db:push"
fi

# ── smoke against a running local server (unchanged) ─────────────────────────
BASE="${COCKPIT_URL:-http://localhost:3000}"
_health=$(curl -sf --max-time 2 "$BASE/api/health" 2>/dev/null || true)
if [ -z "$_health" ]; then
  echo "→ smoke: server not running at $BASE — skipping (start with pnpm run dev or install-app)"
elif ! printf '%s' "$_health" | grep -q '"app":"loki"'; then
  # Identify the APP, not the shape of its answer.
  #
  # Every app in the fleet serves /api/health from the same template, so
  # `"commit"` is present in all of them — it identifies a shape, not a
  # product. On 2026-09-22 a Heidi dev server holding :3000 satisfied that
  # test, Loki's 48-route auth smoke ran against it, and 23 routes "failed"
  # with 404 on a verdict about somebody else's app (confirmed by reading
  # /proc/<pid>/cwd on the process holding the port).
  #
  # A Loki older than the commit that added `app` to the payload is skipped
  # here too. That is the right way to be wrong: a gate that stays quiet
  # costs a run of the smoke, and one that fails loudly for the wrong reason
  # costs the next person's trust in every verdict it gives.
  echo "→ smoke: server at $BASE is NOT Loki — skipping (it answered: $(printf '%s' "$_health" | head -c 80))"
elif printf '%s' "$_health" | grep -q '"state":"unconfigured"'; then
  # A RUNNING server is not a SMOKEABLE server.
  #
  # The check above answers "is this Loki"; this one answers "can it serve
  # data". A Loki process with no database satisfies every identity test and
  # 404s every database-backed route, so the hook failed 23 of 48 routes on
  # changes that could not possibly have caused it (CSS, a copy string, a
  # sort comparator). Observed twice on 2026-09-22; both pushes went out
  # --no-verify and CI passed the identical bundle each time.
  #
  # That is the worst shape a gate can take: it blocks correct work, names
  # the wrong cause, and trains you to bypass it — after which it protects
  # nothing. The health payload already says `schema.state`, so the hook had
  # the fact it needed and simply did not look.
  echo "→ smoke: server at $BASE has no database (schema: unconfigured) — skipping"
  echo "  It answers /api/health but 404s every data route, so smoking it tests"
  echo "  the server's state, not your change. Fix with: pnpm run db:push"
else
  echo "→ smoke: Loki server detected at $BASE"
  pnpm run smoke
fi

# ── prod dogfood (unchanged; self-skips without SMOKE_PRIVATE_PIN) ───────────
echo "→ test:pre-push-prod-dogfood"
pnpm run test:pre-push-prod-dogfood

echo "→ deploy: handled by GitHub Actions (deploy.yml, DEPLOY_VIA_CI=true) after CI passes on main"
