#!/usr/bin/env bash
#
# pre-push — block local `git push` when the codebase fails to build/test.
#
# See doc/PRDs/PRD-Git-Hook-Pre-Push-Release-Check.md.
#
# Mirrors the .vscode/tasks.json `check: safe-to-push` compound: builds Debug,
# builds Release (catches unguarded dbg_prn/trc_prn and other Debug-only-symbol
# leakage), then runs the test suite.  Short-circuits on first failure.
#
# Activate per-clone (one-time setup):
#     git config core.hooksPath tools/git-hooks
#
# Bypass for emergencies:
#     git push --no-verify

# Git pipes one line per ref being pushed on stdin:
#     <local-ref> <local-sha> <remote-ref> <remote-sha>
# We only gate pushes destined for refs/heads/main.  Pushes to feature
# branches skip the gate so iterative work doesn't pay the full
# build+test cost; CI / a manual `check: safe-to-push` task covers those
# branches' eventual landing on main.
ZERO_SHA="0000000000000000000000000000000000000000"
gate_main=0
while read -r local_ref local_sha remote_ref remote_sha
do
    # Branch deletion (local SHA all zeros) -- nothing to verify.
    [ "$local_sha" = "$ZERO_SHA" ] && continue
    case "$remote_ref" in
        refs/heads/main) gate_main=1 ;;
    esac
done

if [ "$gate_main" -eq 0 ]
then
    echo "[pre-push] skip: no ref targets refs/heads/main"
    exit 0
fi

REPO_ROOT="$(git rev-parse --show-toplevel)"
cd "$REPO_ROOT" || exit 1

run_step()
{
    local label="$1"
    shift
    echo "[pre-push] running: $label"
    if ! "$@"
    then
        echo
        echo "[pre-push] FAILED: $label"
        echo "[pre-push] push aborted.  Bypass with: git push --no-verify"
        exit 1
    fi
}

# Formatting gate — check only the diff destined for main, and only when a
# clang-format is actually installed. The tree as a whole is intentionally not
# clang-format-clean (heavy hand-alignment), so we never format-check it wholesale;
# tools/format.sh --since limits the check to files this branch touched. Clones
# without LLVM installed (format.sh warns) simply skip this step rather than block.
#
# ADVISORY, not a gate (2026-11-18): clang-format cannot express parts of the house
# style -- `} break;` on one line, two spaces before a trailing comment -- so its
# "fix" damages ordinary ReMoM code. The check still prints what it would change.
if command -v clang-format-20 >/dev/null 2>&1 || command -v clang-format >/dev/null 2>&1
then
    echo "[pre-push] running: format: changed vs main (advisory)"
    if ! ./tools/format.sh check --since origin/main
    then
        echo "[pre-push] format: advisory only -- not blocking the push"
    fi
else
    echo "[pre-push] skip format check: clang-format not found (install LLVM 20 to enable)"
fi

run_step "build: MSVC-debug"   cmake --build --preset MSVC-debug
run_step "build: MSVC-release" cmake --build --preset MSVC-release
run_step "test:  MSVC-release" ctest --preset MSVC-release

echo "[pre-push] OK — push allowed"
exit 0
