#!/usr/bin/env bash
# Generate and validate the selected vault graph before accepting a commit.
set -euo pipefail

framework_root="$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")/.." && pwd)"
vault_root="${1:-${KNOWLEDGE_BASE_ROOT:-$framework_root}}"
echo "[pre-commit] Generating and validating graph..."
"${PYTHON:-python3}" "$framework_root/scripts/generate-graph.py" --vault-root "$vault_root" --write --validate

if ! git -C "$vault_root" ls-files --error-unmatch index/graph.json >/dev/null 2>&1 || \
   ! git -C "$vault_root" diff --quiet -- index/graph.json; then
	echo "[pre-commit] index/graph.json was modified by generation."
	echo "[pre-commit] Stage the generated index/graph.json before committing."
	exit 1
fi
