#!/bin/sh
# Owen Graphite v3 pre-commit hook
# - builds ignored dist/theme-v3.css from src/ and verifies freshness
# - verifies root theme.css matches the fresh bundle
# - checks release metadata, Style Settings, docs/assets, and CSS compatibility budget
# - runs the Live Preview hit-routing audit
# - runs the PDF header/footer marginalia audit
# - runs the duplicate-selector audit (informational)
# Install with:
#   ln -sf ../../dev/scripts/hooks/pre-commit .git/hooks/pre-commit
#   chmod +x dev/scripts/hooks/pre-commit
set -e

repo_root=$(git rev-parse --show-toplevel)
cd "$repo_root"

if [ -x .venv/bin/python ]; then
    PY=.venv/bin/python
elif [ -x .venv/Scripts/python.exe ]; then
    PY=.venv/Scripts/python.exe
else
    PY=python3
fi

changed=$(git diff --cached --name-only)

"$PY" dev/scripts/validation_plan.py --run-safe

if printf '%s\n' "$changed" | grep -Eq '^(src/|theme\.css|manifest\.json|CHANGELOG\.md|README\.md|screenshots/|dev/WIKI/MAP/)'; then
    "$PY" dev/scripts/bundle_v3.py
    "$PY" dev/scripts/bundle_v3.py --check
    "$PY" - <<'PY'
from pathlib import Path

theme = Path("theme.css").read_text(encoding="utf-8")
bundle = Path("dist/theme-v3.css").read_text(encoding="utf-8")
if theme != bundle:
    raise SystemExit("theme.css is stale vs dist/theme-v3.css; promote and stage the fresh bundle copy")
PY
    "$PY" dev/scripts/release_check.py --skip-bundle
else
    "$PY" dev/scripts/audit_docs_assets.py
    "$PY" dev/scripts/audit_wiki_consistency.py
fi

"$PY" dev/scripts/audit_runtime_evidence_requirements.py --strict || {
    echo "Runtime evidence strict check failed. Add evidence or avoid claiming runtime correctness." >&2
    exit 1
}

