#!/bin/sh
# pre-commit, two jobs:
#   (0) block leftover git conflict markers in staged files (fast local mirror of the CI merge-hygiene gate);
#   (1) auto-refresh the §17 diagrams when docs/SYSTEM_DESIGN.md changes, so the committed SVG/PNG never
#       drift from the Mermaid sources in the doc (the single source of truth).
#
# Activate with:  make hooks   (sets git config core.hooksPath scripts/git-hooks)
set -eu

# 0. Block any commit that still carries leftover git conflict markers. Runs on EVERY commit, before the
#    diagram path below. The check + its regex rationale (why the bare `=======` separator is omitted)
#    live in the SINGLE SOURCE OF TRUTH shared with the CI merge-hygiene gate + the PreToolUse hook;
#    `--staged` scans the index (the content about to be committed). `if ! …; then` is safe under
#    `set -e` (a non-zero exit in the condition is swallowed rather than aborting the hook).
if ! python3 scripts/ci/check_conflict_markers.py --staged; then
  echo "            (emergency bypass: git commit --no-verify — but the CI merge-hygiene gate still blocks main)" >&2
  exit 1
fi

# 1. Only act when the design doc is part of this commit.
if ! git diff --cached --name-only 2>/dev/null | grep -qx "docs/SYSTEM_DESIGN.md"; then
  exit 0
fi

# 2. Already in sync? Browser-free check — nothing to do.
if python3 docs/diagrams/render.py --check >/dev/null 2>&1; then
  exit 0
fi

echo "pre-commit: SYSTEM_DESIGN.md §17 changed → refreshing diagrams…"

# 3. Re-render (needs the local mermaid CLI + system Chrome) and stage the results.
if [ -x docs/diagrams/node_modules/.bin/mmdc ]; then
  python3 docs/diagrams/render.py
  git add docs/diagrams/*.mmd docs/diagrams/*.svg docs/diagrams/*.png
  echo "pre-commit: diagrams refreshed and staged."
else
  echo "pre-commit: diagram sources changed but the renderer isn't installed." >&2
  echo "            run: make diagrams-install && make diagrams && git add docs/diagrams" >&2
  exit 1
fi
