#!/usr/bin/env bash
# Hunt the intermittent -net render glitch: run the 2-node session N times, snapshot
# BOTH nodes' backbuffers each run, and flag runs where the two nodes DIVERGE (a glitched
# node renders notably darker / different: camera-inside or shadow-clip). Snapshots kept
# per run for inspection.
cd /c/git/bt411/content || exit 1
RUNS=${1:-6}
rm -f /c/git/bt411/scratchpad/hunt_*.png /c/git/bt411/scratchpad/hunt_div.txt
for n in $(seq 1 "$RUNS"); do
  taskkill //F //IM btl4.exe >/dev/null 2>&1; taskkill //F //IM python.exe >/dev/null 2>&1; sleep 1
  rm -f mp_a.log mp_b.log /c/git/bt411/scratchpad/shot_1501.png /c/git/bt411/scratchpad/shot_1601.png
  BT_LOG=mp_b.log BT_AFFINITY=0x2 BT_MP_LOG=1 BT_SHOT="C:/git/bt411/scratchpad/shot_1601.png" \
    ../build/Debug/btl4.exe -egg MP.EGG -net 1601 >/dev/null 2>&1 &
  sleep 2
  BT_LOG=mp_a.log BT_AFFINITY=0x1 BT_MP_LOG=1 BT_SHOT="C:/git/bt411/scratchpad/shot_1501.png" \
    ../build/Debug/btl4.exe -egg MP.EGG -net 1501 >/dev/null 2>&1 &
  sleep 5
  python ../tools/btconsole.py MP.EGG 127.0.0.1:1501 127.0.0.1:1601 >/dev/null 2>&1 &
  # wait for both shots to exist + one more write cycle, then copy between writes
  for i in $(seq 1 20); do [ -f /c/git/bt411/scratchpad/shot_1501.png ] && [ -f /c/git/bt411/scratchpad/shot_1601.png ] && break; ping -n 2 127.0.0.1 >/dev/null 2>&1; done
  ping -n 6 127.0.0.1 >/dev/null 2>&1
  for tag in 1501 1601; do
    for a in 1 2 3 4; do
      cp "/c/git/bt411/scratchpad/shot_${tag}.png" "/c/git/bt411/scratchpad/hunt_${n}_${tag}.png" 2>/dev/null
      python -c "from PIL import Image; Image.open('/c/git/bt411/scratchpad/hunt_${n}_${tag}.png').load()" 2>/dev/null && break
      ping -n 4 127.0.0.1 >/dev/null 2>&1
    done
  done
  taskkill //F //IM btl4.exe >/dev/null 2>&1; taskkill //F //IM python.exe >/dev/null 2>&1
  # divergence metric
  python - "$n" <<PY
import sys,numpy as np
from PIL import Image
n=sys.argv[1]
try:
    A=np.array(Image.open(f"/c/git/bt411/scratchpad/hunt_{n}_1501.png").convert("RGB")).astype(float)
    B=np.array(Image.open(f"/c/git/bt411/scratchpad/hunt_{n}_1601.png").convert("RGB")).astype(float)
    ma,mb=A.mean(0).mean(0),B.mean(0).mean(0)
    # brightness + darkness fraction (camera-inside => lots of dark pixels)
    dfa=(A.mean(2)<20).mean(); dfb=(B.mean(2)<20).mean()
    div=abs(ma-mb).max()
    flag="  <== DIVERGENT" if (div>18 or abs(dfa-dfb)>0.15) else ""
    line=f"run {n}: 1501 mean={ma.round(1)} dark={dfa:.2f} | 1601 mean={mb.round(1)} dark={dfb:.2f} | maxDiv={div:.1f}{flag}"
except Exception as e:
    line=f"run {n}: ERROR {e}"
print(line)
open("/c/git/bt411/scratchpad/hunt_div.txt","a").write(line+"\n")
PY
done
echo "=== HUNT DONE ($RUNS runs) ==="
