#!/bin/sh
# pre-commit hook: validates the knowledge base before every commit.
#
# INSTALL:
#   cp scripts/pre-commit .git/hooks/pre-commit
#   chmod +x .git/hooks/pre-commit
#
# This hook runs `node knowledge.js validate` and blocks the commit if validation
# fails. It only runs the check when knowledge/ files are part of the staged changes,
# so it does not slow down commits that don't touch the knowledge base.
#
# To bypass in an emergency (strongly discouraged):
#   git commit --no-verify -m "your message"

set -e

# Find the repo root (works even when called from a subdirectory)
REPO_ROOT="$(git rev-parse --show-toplevel)"

# Check whether any staged files are under knowledge/
STAGED_KNOWLEDGE=$(git diff --cached --name-only | grep '^knowledge/' || true)

if [ -z "$STAGED_KNOWLEDGE" ]; then
    # No knowledge/ files staged — skip the check
    exit 0
fi

echo "🔍 knowledge/ files staged — running validate..."
echo ""

# Run validate from the repo root so knowledge.js finds the right paths
cd "$REPO_ROOT"

if node knowledge.js validate; then
    echo ""
    echo "✓ knowledge base valid — proceeding with commit."
    exit 0
else
    echo ""
    echo "✗ COMMIT BLOCKED: knowledge.js validate reported errors."
    echo ""
    echo "  Fix the errors above, then stage your changes and commit again."
    echo "  To skip this check in an emergency: git commit --no-verify"
    echo ""
    exit 1
fi
