#!/usr/bin/env bash
# Lane-2 repin battery. Standing driver form (.spt-clippy.sh, 2026-09-08):
# pre-seed a VOID sentinel BEFORE the leg so a force kill cannot mint an
# absence that reads clean; an integer OVERWRITES it; the reader refuses
# anything that is not a bare integer; a stale outdir REFUSES (exit 4).
set -u
GW=$1; OUT=$GW/.spt-r2repin
mkdir "$OUT" 2>/dev/null || { echo "REFUSE: outdir exists"; exit 4; }
cd "$GW" || exit 9
# A battery launched from a perch INHERITS the endpoint identity and every
# daemon-stopping cell is then REFUSED by design (2026-09-06 W0).
unset OWL_SESSION_ID SPT_AGENT_ID SPT_ENDPOINT_ID SPT_HOME SPT_API_TOKEN

echo "head: $(git rev-parse HEAD)" > "$OUT/head.txt"
git log --oneline -2 >> "$OUT/head.txt"

# ---- fixtures FIRST, then census them BY NAME (a missing fixture reds a cell
# ---- for a reason that has nothing to do with the change under test).
echo "VOID:unfinished" > "$OUT/build.exit"
cargo build -p spt -p spt-daemon -p mock-adapter --bins > "$OUT/build.raw" 2>&1
echo $? > "$OUT/build.exit"
BIN=target/debug
{
  for f in mock-session mock-shell service_fixture gh_fixture git_fixture \
           post_step_fixture translate_proof_fixture capture-player console-mode-probe; do
    if [ -f "$BIN/$f.exe" ]; then echo "PRESENT $f"; else echo "MISSING $f"; fi
  done
} > "$OUT/fixtures.txt"

# ---- the four cells. gateway by BINARY, the rest by fn name.
run_leg () {
  local tag=$1; shift
  echo "VOID:unfinished" > "$OUT/$tag.exit"
  cargo nextest run -p spt --no-fail-fast "$@" > "$OUT/$tag.raw" 2>&1
  echo $? > "$OUT/$tag.exit"
}
run_leg gateway  -E 'binary(gateway_e2e)'
run_leg poll     -E 'test(api_poll_emits_whole_self_delimiting_events)'
run_leg quick    -E 'test(published_messaging_quickstart_runs_as_written)'
run_leg ioev     -E 'binary(io_events_undriven_kinds_e2e)'

{
  for tag in build gateway poll quick ioev; do
    e=$(cat "$OUT/$tag.exit" 2>/dev/null)
    case "$e" in ''|*[!0-9]*) echo "$tag: EXIT=VOID($e) -- leg did not finish, verdict REFUSED";;
                 *) echo "$tag: exit=$e";; esac
  done
  for tag in gateway poll quick ioev; do
    r="$OUT/$tag.raw"
    echo "--- $tag"
    echo "  Summary-lines=$(grep -c 'Summary' "$r")"
    echo "  run-count=$(grep -oE '[0-9]+ tests? run' "$r" | grep -oE '^[0-9]+' | tail -1)"
    echo "  PASS=$(grep -cE '^ *PASS' "$r")  FAIL=$(grep -cE '^ *FAIL' "$r")"
    echo "  fixture-gap-hits=$(grep -c 'required test fixture' "$r")"
  done
} > "$OUT/census.txt"
echo "DRIVER-DONE"
