#!/usr/bin/env bash
# AAHP pre-push hook - full handoff gate + conformance self-check.
#
# Runs: aahp verify --level prepush
#   Layer 1: MANIFEST checksum integrity
#   Layer 2: content-drift gate
#   Layer 3: commit-pointer freshness (MANIFEST.last_session.commit vs HEAD)
#   Layer 4: TRUST-TTL: check-backed rows re-proven, dated rows judged by expiry
#            (blocking under trustTtl.enforce only after the grace period)
# then: aahp doctor (conformance self-check), when the aahp tooling is resolvable.
#
# Escape hatch: AAHP_SKIP_VERIFY=1 git push ...   (caught by the required CI
# check; do NOT use it to bypass CI). Never use `git push --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 push 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" ]; then
    bash "$VERIFY" "$REPO_ROOT" --level prepush
elif [ "${AAHP_SKIP_VERIFY:-0}" != "1" ] && [ -f "$AAHP_CLI" ] && command -v node >/dev/null 2>&1; then
    node "$AAHP_CLI" verify "$REPO_ROOT" --level prepush
else
    echo "AAHP pre-push: no verify-handoff.sh and no locally installed aahp package, skipping gate." >&2
fi

# Conformance self-check (aahp doctor). Dogfooded on AAHP; opt-in for consumers.
# Runs only when the aahp tooling is resolvable, and honours the same escape
# hatch as the verify gate. A non-zero doctor result blocks the push. Same
# path-only resolution as above: no `npx`, so no registry fallback.
if [ "${AAHP_SKIP_VERIFY:-0}" != "1" ] && command -v node >/dev/null 2>&1; then
    if [ -f "$REPO_ROOT/bin/aahp.js" ]; then
        node "$REPO_ROOT/bin/aahp.js" doctor "$REPO_ROOT" --quiet
    elif [ -f "$AAHP_CLI" ]; then
        node "$AAHP_CLI" doctor "$REPO_ROOT" --quiet
    fi
fi
