#!/usr/bin/env bash
# post-merge hook — advisory lane reclaim (ADR-141, ADR-046).
#
# A `git pull` / `git merge` that brings the trunk forward may have just landed
# one of your branches. That is the moment "which development lanes can I give
# back?" has a new answer — the merge queue lands your branch, so you learn it
# here, on the pull, not on a push you make. So this surfaces TIDY's reclaim
# proposals right after the merge.
#
# It is ADVISORY and PROPOSE-ONLY. It prints what COULD be reclaimed and the
# commands that would do it, and it runs NONE of them — dropping a database is
# the irreversible one, and that stays a thing you type yourself through
# `axi lane`. It never fails the merge: a reclaim hint is not worth blocking a
# pull over, so every path exits 0.
#
# Why a local hook and not a CI job: a lane is local developer-machine state
# (a database, a port pair, a checkout, recorded in ~/.axi/local/lanes.json). A
# cloud CI runner cannot see that file; only a hook on your machine can.
#
# To install (shares one hooks dir across a repo's worktrees):
#   cp scripts/hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge
#
# Opt out any time with AXI_NO_RECLAIM_HINT=1 (set it for scripts and CI).

set -uo pipefail

[ "${AXI_NO_RECLAIM_HINT:-0}" = "1" ] && exit 0

# A runnable CLI without assuming PATH: prefer the platform/consumer command,
# fall back to the module through whatever python is active. Each path asks for
# the machine-readable payload so this script parses data, not a rendering.
run_reclaim() {
  if command -v axi  >/dev/null 2>&1; then axi  hygiene --json reclaim 2>/dev/null; return; fi
  if command -v neut >/dev/null 2>&1; then neut hygiene --json reclaim 2>/dev/null; return; fi
  python -c 'import sys; from axiom.extensions.builtins.hygiene import cli; sys.exit(cli.main(["--json","reclaim"]))' 2>/dev/null
}

out="$(run_reclaim || true)"
[ -z "$out" ] && exit 0

# The payload rides in on an env var, not a pipe: a heredoc already owns the
# script's stdin, so a `printf ... | python - <<PY` would silently feed the
# program nothing. An env var carries multiline JSON intact.
AXI_RECLAIM_JSON="$out" python - <<'PY' || true
import json, os, sys

try:
    data = json.loads(os.environ.get("AXI_RECLAIM_JSON", ""))
except Exception:
    sys.exit(0)

reclaimable = data.get("reclaimable") or []
if not reclaimable:
    # Nothing to reclaim is the common case; stay silent so the hook is not noise.
    sys.exit(0)

n = len(reclaimable)
print()
print(f"lane: {n} lane(s) look reclaimable after this merge "
      f"(proposals only, nothing was run):")
for r in reclaimable:
    print(f"  {r['lane']}: " + "; ".join(r.get("why") or []))
    for cmd in r.get("proposed") or []:
        print(f"      {cmd}")
print("  review these and run them yourself; `axi hygiene reclaim` shows the "
      "full picture. Silence with AXI_NO_RECLAIM_HINT=1.")
PY

exit 0
