#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Fast pre-commit gate. A commit that stages only prose nothing reads (see scripts/hooks/prose-only)
# runs the documentation check. Any other commit keeps generated tables in sync and runs the fast
# test subset, in parallel. The full suite, including slow-marked experiment tests, runs on
# pre-push; see scripts/hooks/pre-push.

set -eu

# A commit made from a linked worktree exports git-internal variables into this
# hook (GIT_DIR, GIT_INDEX_FILE, GIT_WORK_TREE, GIT_PREFIX and
# GIT_CONFIG_PARAMETERS). An inherited GIT_DIR overrides `git -C <dir>`, so the
# suite this hook execs would write its fixture commits and config edits onto
# another repository (the linked worktree's HEAD/index and the shared
# `.git/config`). Scrub the five before the hook's own first Git command, so a
# poisoned environment cannot steer even `git rev-parse` (R17).
unset GIT_DIR GIT_INDEX_FILE GIT_WORK_TREE GIT_PREFIX GIT_CONFIG_PARAMETERS

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

if [ ! -x "$PROJECT_ROOT/.venv/bin/python" ]; then
    exit 0
fi

# --no-renames: a file renamed out of src/ must still list its deleted source path.
if git diff --cached --name-only --no-renames | "$PROJECT_ROOT/scripts/hooks/prose-only"; then
    printf '%s\n' "pre-commit: prose-only change; running the documentation check instead of the suite."
    # Local links only: a third-party outage must not block a commit.
    CHECK_DOCS_OFFLINE=1 exec "$PROJECT_ROOT/scripts/check-docs"
fi

"$PROJECT_ROOT/.venv/bin/python" "$PROJECT_ROOT/scripts/tables.py"
exec "$PROJECT_ROOT/scripts/check-tests" --fast --parallel
