#!/usr/bin/env bash
# AAHP pre-commit hook - fast handoff gate.
#
# Runs: aahp verify --level precommit
#   Layer 1: MANIFEST checksum integrity
#   Layer 2: content-drift gate (code changed => STATUS.md + MANIFEST.json must change)
#
# This is intentionally fast (no TTL parse, no network). The full gate runs in
# pre-push and in CI.
#
# Escape hatch: AAHP_SKIP_VERIFY=1 git commit ...   (caught by the required CI
# check; do NOT use it to bypass CI). Never use `git commit --no-verify`.
#
# Installed by: scripts/install-hooks.sh

set -euo pipefail

REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || echo ".")"
VERIFY="$REPO_ROOT/scripts/verify-handoff.sh"

# Resolve the gate: prefer the vendored script (full AAHP checkout); otherwise
# fall back to the LOCALLY INSTALLED aahp package (npm-install consumer). If
# neither is present, skip. AAHP_SKIP_VERIFY=1 disables the CLI fallback locally
# (the vendored script honours the same escape hatch internally).
#
# The fallback is a filesystem test on an exact path, never `npx`. Earlier
# versions of this hook guarded with `npx --no-install aahp --version`, with
# stdout and stderr discarded. On a consumer with the hooks installed but no
# local package, that guard asked registry.npmjs.org about the UNSCOPED name
# `aahp`, which this project does not own, on every commit before npx refused
# (measured on npm 10 to 12, AAHP docs/adr/ADR-013.md). It stayed closed only because of
# how the `npx` binary maps `--no-install`; `npm exec --no-install` on npm 10
# and 11 downloads and runs whatever the registry returns. A `[ -f ]`
# test cannot reach the network and cannot resolve any name but the scoped one.
AAHP_CLI="$REPO_ROOT/node_modules/@elvatis_com/aahp/bin/aahp.js"

if [ -f "$VERIFY" ] || [ -x "$VERIFY" ]; then
    bash "$VERIFY" "$REPO_ROOT" --level precommit
elif [ "${AAHP_SKIP_VERIFY:-0}" != "1" ] && [ -f "$AAHP_CLI" ] && command -v node >/dev/null 2>&1; then
    node "$AAHP_CLI" verify "$REPO_ROOT" --level precommit
else
    echo "AAHP pre-commit: no verify-handoff.sh and no locally installed aahp package, skipping gate." >&2
    exit 0
fi
