#!/usr/bin/env bash
# Pre-commit gate: reject a commit whose staged markdown fails any bound
# COMMIT event action (squadron.frontmatter-gate by default; a project's
# events.yaml may add more). Install once with:
#   git config core.hooksPath .githooks
#
# A hook that silently skips when its tool is missing enforces nothing while
# appearing to work, so a failure to launch `uv` is a hard non-zero exit here
# rather than a pass-through.
set -u

staged_files=()
while IFS= read -r -d '' file; do
  staged_files+=("$file")
done < <(git diff --cached --name-only --diff-filter=ACMR -z -- '*.md')

if [ "${#staged_files[@]}" -eq 0 ]; then
  exit 0
fi

if ! command -v uv >/dev/null 2>&1; then
  echo "pre-commit: 'uv' is not on PATH — cannot run sq events fire commit" >&2
  echo "pre-commit: install uv and squadron, or bypass this commit with --no-verify" >&2
  exit 1
fi

uv run --quiet sq events fire commit -- "${staged_files[@]}"
status=$?

if [ "$status" -eq 2 ]; then
  echo "pre-commit: sq events fire commit could not run (see above)." >&2
  echo "pre-commit: common causes: this repo is not a registered cf project (run 'cf init' once)," >&2
  echo "pre-commit: a broken plugin declared in events.yaml, or a malformed events.yaml." >&2
  echo "pre-commit: or bypass this commit with 'git commit --no-verify'." >&2
elif [ "$status" -ne 0 ]; then
  echo "pre-commit: sq events fire commit failed (exit $status)." >&2
  echo "pre-commit: fix the violations above, or bypass with 'git commit --no-verify'." >&2
fi

exit "$status"
