#!/bin/bash
# Floaty + capture ralph (2.0.83): mirrors the REAL user flow — waits for the page to SETTLE
# (auto-login navigation done) before clicking/emitting, like a human hand does. Asserts:
# instant overlay, capture -> toast, drawings fade.
TGT=AdomLapper; ROUNDS=${1:-3}; fail=0
ab(){ adom-bridge-cli --target $TGT "$@" 2>&1; }
for r in $(seq 1 $ROUNDS); do
  ab pup_open_window '{"sessionId":"rf","url":"https://wiki.adom.inc/adom/pup-bridge","foreground":false}' --ai-thread "floaty-ralph" >/dev/null 2>&1
  # settle: URL stable across 2 polls 3s apart AND readyState complete (auto-login nav finished)
  prev=""; for i in 1 2 3 4 5 6 7 8; do
    cur=$(ab pup_eval '{"sessionId":"rf","expr":"document.readyState + \" \" + location.href"}' --ai-thread "floaty-ralph" 2>/dev/null | python3 -c "import sys,json;print(json.load(sys.stdin).get('result'))" 2>/dev/null)
    [ -n "$cur" ] && [ "$cur" = "$prev" ] && case "$cur" in complete*) break;; esac
    prev="$cur"; sleep 3
  done
  ab pup_floaty_click '{"sessionId":"rf"}' --ai-thread "floaty-ralph" >/dev/null 2>&1
  sleep 1
  ov=$(ab pup_eval '{"sessionId":"rf","expr":"document.getElementById(\"__pup_annotate\") ? \"yes\" : \"no\""}' --ai-thread "floaty-ralph" | python3 -c "import sys,json;print(json.load(sys.stdin).get('result'))" 2>/dev/null)
  ab pup_eval '{"sessionId":"rf","expr":"(() => { window.__pupAnnotateResult = { done: true, quick: true, shapes: 1, seq: 1, ts: Date.now(), bbox: { x: 80, y: 80, w: 260, h: 170 } }; return \"emit\"; })()"}' --ai-thread "floaty-ralph" >/dev/null 2>&1
  # toast within 8s (watcher 500ms poll + screencast + sharp)
  tst="no-toast"; for i in 1 2 3 4; do
    sleep 2
    t=$(ab pup_eval '{"sessionId":"rf","expr":"document.getElementById(\"__pup_ann_toast\") ? \"toast\" : \"no-toast\""}' --ai-thread "floaty-ralph" | python3 -c "import sys,json;print(json.load(sys.stdin).get('result'))" 2>/dev/null)
    [ "$t" = "toast" ] && tst="toast" && break
  done
  sleep 4
  fade=$(ab pup_eval '{"sessionId":"rf","expr":"document.getElementById(\"__pup_annotate\") ? \"still-there\" : \"faded\""}' --ai-thread "floaty-ralph" | python3 -c "import sys,json;print(json.load(sys.stdin).get('result'))" 2>/dev/null)
  ab pup_close_window '{"sessionId":"rf"}' --ai-thread "floaty-ralph" >/dev/null 2>&1
  sleep 3
  st="r$r overlay=$ov toast=$tst fade=$fade"
  if [ "$ov" = "yes" ] && [ "$tst" = "toast" ] && [ "$fade" = "faded" ]; then echo "  PASS $st"; else echo "  FAIL $st"; fail=$((fail+1)); fi
done
echo "FLOATY RALPH DONE | FAILURES: $fail"