#!/bin/bash
# Ralph test for pup JUMP-LIST tasks: each round opens wiki windows, then fires the ACTUAL
# jump-list task commands through the REAL deployed launcher (powershell -File launcher verb b64),
# asserting the observable effect: view-toggle + owner-info return success, Close ALL empties.
TGT=AdomLapper
ROUNDS=${1:-5}
LAUNCHER='C:\\Users\\john\\AppData\\Local\\Adom Bridge\\pup-jumplist-call.ps1'
ab(){ adom-bridge-cli --target $TGT "$@" 2>&1; }
count(){ ab pup_list_windows '{}' --ai-thread rjl 2>&1 | python3 -c "import sys,json;print(len(json.load(sys.stdin).get('sessions') or []))" 2>/dev/null; }
# fire a task through the real launcher exactly as a taskbar click does
fire(){ # $1 verb  $2 json
  local b64=$(python3 -c "import base64,sys;print(base64.b64encode(sys.argv[1].encode()).decode())" "$2")
  ab shell_execute "{\"command\":\"powershell.exe -NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File \\\"$LAUNCHER\\\" $1 $b64\",\"reason\":\"ralph jumplist: fire $1 via real launcher (taskbar-click path)\"}" --ai-thread rjl >/dev/null 2>&1
}
fail=0
for r in $(seq 1 $ROUNDS); do
  ab pup_open_window '{"url":"https://wiki.adom.inc/adom/pup-bridge","foreground":false}' --ai-thread "rjl-$r-a" >/dev/null 2>&1
  ab pup_open_window '{"url":"https://wiki.adom.inc/adom/pup-bridge","foreground":false}' --ai-thread "rjl-$r-b" >/dev/null 2>&1
  sleep 6
  pre=$(count)
  # owner-info + view-toggle on window a (observable: no error, window survives)
  fire pup_window_info "{\"sessionId\":\"ai-rjl-$r-a\"}"
  fire pup_wiki_set_view "{\"sessionId\":\"ai-rjl-$r-a\",\"view\":\"public\"}"
  sleep 3
  mid=$(count)
  # Close ALL via the launcher — the click John reported broken
  fire pup_close "{}"
  sleep 5
  post=$(count)
  prob=""
  [ "$pre" -lt 2 ] && prob="$prob OPEN-FAIL($pre)"
  [ "$mid" != "$pre" ] && prob="$prob VIEW/INFO-CHANGED-COUNT($pre->$mid)"
  [ "$post" != "0" ] && prob="$prob CLOSE-ALL-LEFT($post)"
  if [ -n "$prob" ]; then echo "  r$r pre=$pre mid=$mid post=$post ->$prob"; fail=$((fail+1)); fi
  echo "round $r: opened=$pre after-toggle=$mid after-closeall=$post  (running fails=$fail)"
done
echo "===================="
echo "JUMPLIST RALPH DONE: $ROUNDS rounds | FAILURES: $fail"