#!/usr/bin/env bash
# Microwave pre-commit hook. Installed by hooks/install-hooks.sh (or .ps1).
# Per-file gates (brief, schema, testable, embodiment) run on the STAGED bytes
# of each changed agent card. Anti-dup needs the registry index, and the
# repo-wide gates (wiki, slop, docs) scan the tree, so those run on the working
# tree. CI re-runs everything on the actual commit: that is the final guarantee.
set -euo pipefail

PY="$(command -v python3 || command -v python || true)"
if [ -z "$PY" ]; then
  echo "pre-commit: python3 is required to run the Microwave gates" >&2
  exit 1
fi

status=0
tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT

while IFS= read -r -d '' card; do
  case "$card" in
    wiki/agents/*README*|wiki/_staging/*README*) continue ;;
    wiki/agents/*.md|wiki/_staging/*.md)
      staged="$tmpdir/$(basename "$card")"
      git show ":$card" > "$staged"
      # per-file gates: validate the staged blob (the bytes being committed)
      "$PY" gates/gate_brief.py "$staged" || status=1
      "$PY" gates/gate_schema.py "$staged" || status=1
      "$PY" gates/gate_testable.py "$staged" || status=1
      "$PY" gates/gate_embodiment.py "$staged" || status=1
      # anti-dup and uses need the registry index: validate the working tree
      "$PY" gates/gate_antidup.py "$card" || status=1
      "$PY" gates/gate_uses.py "$card" || status=1
      ;;
  esac
done < <(git diff --cached --name-only -z --diff-filter=ACM)

# repo-wide gates, on the working tree
"$PY" gates/gate_wiki.py || status=1
"$PY" gates/gate_slop.py || status=1
"$PY" gates/gate_docs.py || status=1

exit $status
