#!/usr/bin/env bash
# releases#294 Finding 1 — base-vs-head poll-margin comparison.
# Design per doyle's amended plan (all four peer corrections folded in):
#   - instrument, do not infer: hertz's IR95-CONTRACT / IR95-SYNC lines carry the margins
#   - --success-output immediate: a PASSING arm still prints them (deployah's correction)
#   - baseline is de5a44bc (current main), NOT a2f335f8 (the released cut) (todlando's sha hygiene)
#   - alternate the PAIR ORDER A/B then B/A: a fixed A/B/A/B leaves B always later
#     within the pair, so monotone box drift lands on B every time (hertz's correction)
#   - census at START and END of every leg: "runner free" and "box quiet" are different
#     states (deployah). Occupancy is recorded as a CONDITION, never as an explanation —
#     it was measured HIGHER on the FASTER pre-milestone phase.
set -u   # NOT -e: a red leg is data, and the script must survive it to run the rest.

R="C:/Users/decid/Documents/projects/spt-core"
BASE="$R/.worktrees/rca-base"   # c4109a58 = de5a44bc + instrumentation
HEAD="$R/.worktrees/rca-head"   # 161eb554 = a9e786b2 + instrumentation
OUT="${OUT:-$R/.worktrees/rca-head/rca294-out}"
REPS="${REPS:-3}"
mkdir -p "$OUT"

census() { # $1 = label written into the census line
  powershell -NoProfile -Command "
    \$p=(Get-Process).Count
    \$s=@(Get-Process spt -ErrorAction SilentlyContinue).Count
    \$f=[math]::Round((Get-PSDrive C).Free/1GB,2)
    Write-Output ('CENSUS $1 utc={0} procs={1} spt_exe={2} freeGiB={3}' -f (Get-Date).ToUniversalTime().ToString('o'),\$p,\$s,\$f)
  " 2>/dev/null
}

leg() { # $1=arm(base|head)  $2=cell(contract|sync)  $3=rep
  local arm="$1" cell="$2" rep="$3" wt pkg tst filt tag t0 t1 rc
  case "$arm" in base) wt="$BASE";; head) wt="$HEAD";; esac
  case "$cell" in
    contract) pkg=spt;        tst=contract_e2e; filt='test(live_agent_lifecycle_e2e)';;
    sync)     pkg=spt-daemon; tst=sync;         filt='test(two_tier_sync_lands_and_gate_refuses_server_side)';;
  esac
  tag="rep${rep}-${cell}-${arm}"
  echo "===== LEG $tag ====="
  census "START $tag"
  t0=$(date -u +%s.%N)
  ( cd "$wt" && cargo nextest run --no-fail-fast --success-output immediate \
      --test-threads=1 -p "$pkg" --test "$tst" -E "$filt" ) >"$OUT/$tag.log" 2>&1
  rc=$?
  t1=$(date -u +%s.%N)
  census "END   $tag"
  echo "LEG $tag rc=$rc wall_s=$(awk -v a="$t0" -v b="$t1" 'BEGIN{printf "%.2f", b-a}')"
  grep -E '^(IR95-CONTRACT|IR95-SYNC)' "$OUT/$tag.log" || echo "  (no IR95 line in $tag.log)"
  grep -E '^\s+(PASS|FAIL|TRY)' "$OUT/$tag.log" | head -3
}

# PRE-BUILD THE FIXTURES. contract_e2e asserts on `sibling_bin()` (crates/spt/tests/common/mod.rs:263)
# and mock-session/mock-shell come from the mock-adapter package, which `nextest --no-run` does NOT
# build. Found by a smoke leg before the real run: without this every contract leg FAILS in 0.025s
# at the precondition, which would have looked like six red arms instead of a missing fixture.
for wt in "$BASE" "$HEAD"; do
  echo "PREBUILD fixtures in $wt"
  ( cd "$wt" && cargo build -q -p mock-adapter ) || { echo "FIXTURE BUILD FAILED in $wt"; exit 1; }
  for f in mock-session mock-shell; do
    [ -f "$wt/target/debug/$f.exe" ] || { echo "FIXTURE MISSING after build: $wt/target/debug/$f.exe"; exit 1; }
  done
done

echo "RCA294 ARMS  base=$(git -C "$BASE" rev-parse --short HEAD)  head=$(git -C "$HEAD" rev-parse --short HEAD)  reps=$REPS"
echo "started_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
for rep in $(seq 1 "$REPS"); do
  for cell in contract sync; do
    # alternate the pair order: odd reps base-first, even reps head-first
    if [ $((rep % 2)) -eq 1 ]; then order="base head"; else order="head base"; fi
    for arm in $order; do leg "$arm" "$cell" "$rep"; done
  done
done
echo "finished_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "===== MARGIN SUMMARY ====="
grep -H -E '^(IR95-CONTRACT|IR95-SYNC)' "$OUT"/*.log 2>/dev/null || echo "(none)"
