#!/bin/sh
# 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

# 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
