#!/bin/sh
# Aether Quant pre-commit secret guard (Phase V2-22 security).
#
# Blocks a commit that would publish a secret: a populated secret field in the
# tracked lean.json, or a tracked real `.env` file. All detection lives in
# `aq secrets-check` (execution/secret_scan.py) - this hook just invokes it.
#
# Enable once per clone (opt-in, so it never surprises a fresh checkout):
#     git config core.hooksPath .githooks
#
# Runs under git's POSIX sh (git-bash on Windows), so keep it portable.

set -e

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

# Prefer the installed `aq` console script; fall back to running the module
# directly with whichever Python is on PATH (venv-activated shells get theirs).
if command -v aq >/dev/null 2>&1; then
    aq secrets-check
elif command -v python >/dev/null 2>&1; then
    python aq_cli.py secrets-check
elif command -v python3 >/dev/null 2>&1; then
    python3 aq_cli.py secrets-check
else
    echo "pre-commit: could not find 'aq' or 'python' to run secrets-check" >&2
    exit 1
fi

# V6.6.4 - the library gate: a public function that no aether_quant facade exports blocks the commit (scripts/library_gate.py). It reads the source and imports nothing.
if command -v python >/dev/null 2>&1; then
    python scripts/library_gate.py
elif command -v python3 >/dev/null 2>&1; then
    python3 scripts/library_gate.py
fi

# V6.6.7 (#361) - every install hash-pinned, as the OpenSSF Scorecard reads it (scripts/scorecard_pins.py, about a second).
if command -v python >/dev/null 2>&1; then
    python scripts/scorecard_pins.py
elif command -v python3 >/dev/null 2>&1; then
    python3 scripts/scorecard_pins.py
fi

# V6.6.7 (#367) - coverage stays at 100% after every commit (AGENTS.md "Coverage: 100% after every commit"): the tests
# that name each changed module run under coverage. A full `aq test --coverage` newer than the changes passes at once.
# Skip only when that full run is what you just did: AQ_SKIP_COVERAGE_HOOK=1 git commit ...
if [ "${AQ_SKIP_COVERAGE_HOOK:-0}" != "1" ]; then
    start=$(date +%s)
    if command -v aq >/dev/null 2>&1; then
        aq test --coverage --changed
    elif command -v python >/dev/null 2>&1; then
        python aq_cli.py test --coverage --changed
    else
        python3 aq_cli.py test --coverage --changed
    fi
    echo "pre-commit: coverage of the changed modules checked in $(( $(date +%s) - start )) s"
fi
