#!/usr/bin/env bash
# core/hooks/pre-commit — PhaseOps core pre-commit hook
#
# Lightweight pre-commit. Runs `phaseops validate` (meta-validation of
# all PhaseOps artifacts against their JSON Schemas) so broken schemas
# or invalid frontmatter cannot ship.
#
# Adapter-specific checks (linters, static analysis, security scans)
# live under `adapters/<name>/hooks/pre-commit` and are appended at
# install time by `phaseops init` (Phase C).
#
# Escape hatch: PHASEOPS_NO_VALIDATE=1 git commit ...

set -euo pipefail

if [ "${PHASEOPS_NO_VALIDATE:-0}" = "1" ]; then
  exit 0
fi

# Block accidentally committed secret files
staged_env=$(git diff --cached --name-only --diff-filter=AM | grep -E '(^|/)\.env(\..+)?$' || true)
if [ -n "$staged_env" ]; then
  echo "ERROR: refusing to commit .env-style file(s):" >&2
  echo "$staged_env" | sed 's/^/  /' >&2
  echo "Unstage: git restore --staged <file>" >&2
  exit 1
fi

# Run phaseops meta-validation
if [ -x ".venv/bin/phaseops" ]; then
  .venv/bin/phaseops validate
elif command -v phaseops >/dev/null 2>&1; then
  phaseops validate
else
  echo "phaseops not installed — skipping core validate" >&2
fi

# Adapter hooks (if any) are appended below by `phaseops init`.
# ---- ADAPTER HOOKS APPENDED BELOW ----
exit 0
