#!/usr/bin/env bash
# pre-commit hook — keeps the derived port ledger current and runs the
# Linux-only regression nets BEFORE a commit lands, converting the project's
# "agent remembers to run make" convention into an enforced gate.
#
#   1. Regenerate the derived registries (STATUS.md, port-ledger.{json,md},
#      port-debt.{json,md}) and stage them so they always track HEAD with zero
#      manual steps.
#   2. Run Python unit tests when Python tooling changed.
#   3. If any C source/header or test changed, build + run the ASan/UBSan
#      host suite and abort the commit on failure.
#
# Bypass for an emergency / WIP commit:  git commit --no-verify
# Installed via core.hooksPath=tools/git-hooks.

set -euo pipefail
cd "$(git rev-parse --show-toplevel)"

# nix wrapper — python3/make live in the dev shell on this host.
run() { nix develop --command "$@"; }
# Test runs get a scrubbed git environment: git exports GIT_DIR/GIT_INDEX_FILE to
# hooks, and a test that shells out to `git init`/`git add` in a temp repo would
# otherwise act on THIS repository (2026-10-13: a removed test re-initialised the
# shared .git as bare and staged a stray file into the commit's index).
run_tests() {
    env -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE -u GIT_PREFIX \
        -u GIT_COMMON_DIR -u GIT_OBJECT_DIRECTORY -u GIT_ALTERNATE_OBJECT_DIRECTORIES \
        nix develop --command "$@"
}

# --- 1. Regenerate + stage the derived registries ------------------------
# port-debt first (independent), then the ledger (its STATUS headline re-counts
# the same PORT-DEBT markers, so both reflect the staged tree).
if run python3 tools/gen_port_debt.py >/tmp/oc_debt.log 2>&1; then
    git add docs/port-debt.json docs/port-debt.md 2>/dev/null || true
else
    echo "pre-commit: port-debt generation failed:" >&2
    cat /tmp/oc_debt.log >&2
    exit 1
fi
if run python3 tools/gen_port_ledger.py >/tmp/oc_ledger.log 2>&1; then
    git add docs/STATUS.md docs/port-ledger.json docs/port-ledger.md 2>/dev/null || true
else
    echo "pre-commit: port-ledger generation failed:" >&2
    cat /tmp/oc_ledger.log >&2
    exit 1
fi

staged="$(git diff --cached --name-only)"

# --- 2. Run Python tool tests when Python changed ------------------------
if echo "$staged" | grep -qE '^tools/.*\.py$'; then
    echo "pre-commit: Python tools changed → running Python unit suite..."
    if ! run_tests python3 tools/run_python_tests.py >/tmp/oc_pytests.log 2>&1; then
        echo "pre-commit: Python unit suite FAILED — commit aborted:" >&2
        tail -40 /tmp/oc_pytests.log >&2
        exit 1
    fi
    echo "pre-commit: $(tail -1 /tmp/oc_pytests.log)"
fi

# --- 3. Run the host test suite if C code changed ------------------------
if echo "$staged" | grep -qE '^(src/|tests/).*\.(c|h)$'; then
    echo "pre-commit: C sources changed → building + running host suite..."
    if ! run_tests make -C tests run >/tmp/oc_tests.log 2>&1; then
        echo "pre-commit: host test suite FAILED — commit aborted:" >&2
        tail -30 /tmp/oc_tests.log >&2
        echo "(bypass with: git commit --no-verify)" >&2
        exit 1
    fi
    echo "pre-commit: $(grep -oE '[0-9]+ passed' /tmp/oc_tests.log | tail -1)"
fi

# --- 4. FP-model guard when the toolchain/build flags changed ------------
# The x87 invariant (audit §1.3): float math must NOT move to SSE — retail is
# VC6/x87 and every validated function's rounding depends on it. Only the
# Makefile / flake can change the FP model, so gate on those (the exe on disk
# may be stale otherwise). Nightly CI re-checks on a fresh build regardless.
if echo "$staged" | grep -qE '^(src/Makefile|flake\.nix|flake\.lock)$' \
        && [ -f build/openrecet.exe ]; then
    echo "pre-commit: toolchain/build flags changed → checking x87 invariant..."
    if ! run python3 tools/ci/no_sse_math.py build/openrecet.exe; then
        echo "pre-commit: SSE float math detected — commit aborted (rebuild" >&2
        echo "            with the x87 toolchain or fix the flags)" >&2
        exit 1
    fi
fi

exit 0
