#!/bin/bash
# Ralph test for pup taskbar identity: repeatedly open windows (single, concurrent, multi-tab),
# assert EVERY window gets a distinct OS handle + a successful AUMID stamp + an overlay paint,
# and NO collision (two sessions on one handle) and NO stamp FAILED. Closes what it opens each round.
TGT=AdomLapper
LOG=C:/Users/john/.adom/bridge-logs/puppeteer.log
ROUNDS=${1:-8}
ab() { adom-bridge-cli --target $TGT "$@" 2>&1; }
jget() { python3 -c "import sys,json;d=json.load(sys.stdin);print(d.get('$1',''))" 2>/dev/null; }

total_windows=0 fail=0
declare -A allhandles
for r in $(seq 1 $ROUNDS); do
  mode=$((r % 3))
  case $mode in
    1) threads=("rl-$r-a") ;;                                  # single
    2) threads=("rl-$r-a" "rl-$r-b" "rl-$r-c") ;;              # concurrent burst
    0) threads=("rl-$r-a" "rl-$r-b") ;;                        # pair
  esac
  # open (concurrent when >1)
  for t in "${threads[@]}"; do
    ab pup_open_window '{"url":"https://example.com","foreground":false}' --ai-thread "$t" >/dev/null 2>&1 &
  done
  wait
  # round 0: also add tabs to make them multi-tab
  if [ $mode -eq 0 ]; then
    for t in "${threads[@]}"; do
      ab pup_open_tab '{"url":"https://wiki.adom.inc/adom/pup-bridge"}' --ai-thread "$t" >/dev/null 2>&1
    done
  fi
  sleep 13
  # pull the log ONCE for this round and assert
  ab pull_file "{\"filePaths\":[\"${LOG//\//\\\\}\"],\"saveTo\":\"/tmp/ralphlog\"}" --ai-thread "pup-bridge build" >/dev/null 2>&1
  LF=/tmp/ralphlog/puppeteer.log
  for t in "${threads[@]}"; do
    sid="ai-$(echo "$t" | tr 'A-Z' 'a-z')"
    total_windows=$((total_windows+1))
    handle=$(grep -E "\"$sid\" resolved OS handle [0-9]+" "$LF" 2>/dev/null | tail -1 | sed -E 's/.*handle ([0-9]+).*/\1/')
    stamped=$(grep -cE "\"$sid\" stamped appId" "$LF" 2>/dev/null)
    failed=$(grep -cE "\"$sid\".*stamp FAILED" "$LF" 2>/dev/null)
    overlay=$(grep -cE "\"$sid\".*(PAINT|ENFORCED)" "$LF" 2>/dev/null)
    problem=""
    [ -z "$handle" ] && problem="$problem NO-HANDLE"
    [ "$stamped" = "0" ] && problem="$problem NOT-STAMPED"
    [ -n "$handle" ] && [ -n "${allhandles[$handle]}" ] && [ "${allhandles[$handle]}" != "$sid" ] && problem="$problem COLLISION-with-${allhandles[$handle]}"
    [ "$overlay" = "0" ] && problem="$problem NO-OVERLAY"
    [ -n "$handle" ] && allhandles[$handle]=$sid
    if [ -n "$problem" ]; then echo "  r$r $sid hwnd=$handle stamp=$stamped fail=$failed ovl=$overlay ->$problem"; fail=$((fail+1)); fi
  done
  # cleanup this round's windows
  for t in "${threads[@]}"; do ab pup_close_window '{}' --ai-thread "$t" >/dev/null 2>&1; done
  sleep 2
  echo "round $r ($([ $mode -eq 1 ] && echo single || ([ $mode -eq 2 ] && echo concurrent-3 || echo pair-multitab))): ${#threads[@]} windows, running fails=$fail"
done
echo "===================="
echo "RALPH DONE: $total_windows windows across $ROUNDS rounds | FAILURES: $fail | distinct handles: ${#allhandles[@]}"
