#!/usr/bin/env bash
# ── DASHBOARD RALPH TEST ───────────────────────────────────────────────────────────────────────
# Drives every dashboard action end to end and ASSERTS the effect, instead of shipping and hoping.
# John: "have you even bothered to ralph test yourself?" - no, and it showed across ~30 broken ships.
# This runs the dashboard's OWN endpoints the way the page buttons do (POST /dashboard/action) and
# checks real state via browser_list_windows after each, so a dead button fails HERE, not on his screen.
set -u
T="dash-ralph"
AD() { timeout 70 adom-desktop --target AdomLapper --ai-thread "$T" "$@" 2>/dev/null; }
py() { python3 -c "$1" 2>/dev/null; }
PORT="${1:-64230}"; BASE="http://127.0.0.1:$PORT"
PASS=0; FAIL=0
ok(){ echo "  PASS: $1"; PASS=$((PASS+1)); }
no(){ echo "  FAIL: $1"; FAIL=$((FAIL+1)); }

curlpost(){ py "import json;print(json.dumps({'command':'curl -s -m 6 -X POST -H \"Content-Type: application/json\" -d '+json.dumps('$2')+' $BASE$1','reason':'dash ralph'}))" > /tmp/cp.json; AD shell_execute "$(cat /tmp/cp.json)" | py "import sys,json;print((json.load(sys.stdin).get('stdout') or '').strip())"; }
curlget(){ py "import json;print(json.dumps({'command':'curl -s -m 6 $BASE$1','reason':'dash ralph'}))" > /tmp/cg.json; AD shell_execute "$(cat /tmp/cg.json)" | py "import sys,json;print((json.load(sys.stdin).get('stdout') or '').strip())"; }
ntabs(){ AD browser_list_tabs "{\"sessionId\":\"$1\"}" | py "import sys,json;d=json.load(sys.stdin);o=d.get('output') or d;o=json.loads(o) if isinstance(o,str) else o;print(len(o.get('tabs',[])))"; }
has(){ AD browser_list_windows | py "import sys,json;d=json.load(sys.stdin);o=d.get('output') or d;o=json.loads(o) if isinstance(o,str) else o;print('yes' if any(s.get('sessionId')=='$1' for s in o.get('sessions',[])) else 'no')"; }

echo "── dashboard ralph test ──"
for s in ralph-a ralph-b; do AD browser_close_window "{\"sessionId\":\"$s\",\"reason\":\"ralph cleanup\",\"takeover\":true}" >/dev/null 2>&1; done

AD browser_open_window "{\"sessionId\":\"ralph-a\",\"url\":\"$BASE/dashboard\",\"reason\":\"ralph: verify the page runs\"}" >/dev/null 2>&1
sleep 6
[ "$(AD browser_eval '{"sessionId":"ralph-a","expr":"typeof SNAP!==\"undefined\" && !!SNAP"}' | py 'import sys,json;print(json.load(sys.stdin).get("result"))')" = "True" ] \
  && ok "page script executes (SNAP defined)" || no "page script did NOT run (SNAP undefined)"

echo "$(curlget /dashboard/events | head -c 20)" | grep -q "data:" && ok "SSE stream emits data" || no "SSE stream empty"
echo "$(curlget /dashboard/icon.svg | head -c 5)" | grep -q "<svg" && ok "icon.svg serves" || no "icon.svg missing"

GRP=$(curlget /dashboard/events | head -1 | sed 's/^data: //' | py 'import sys,json;d=json.load(sys.stdin);print(len(d.get("taskbarButtons",[])),d["counts"]["browsers"])')
BTNS=$(echo "$GRP" | awk '{print $1}'); CHR=$(echo "$GRP" | awk '{print $2}')
[ -n "$BTNS" ] && [ "$BTNS" -le "$CHR" ] 2>/dev/null && ok "taskbar rows ($BTNS) <= chrome procs ($CHR)" || no "more rows ($BTNS) than chrome procs ($CHR)"

AD browser_open_window "{\"sessionId\":\"ralph-b\",\"url\":\"https://example.com\",\"reason\":\"ralph: tab ops\"}" >/dev/null 2>&1
AD browser_open_tab '{"sessionId":"ralph-b","url":"https://example.org"}' >/dev/null 2>&1
sleep 3
T0=$(ntabs ralph-b)
curlpost /dashboard/action '{"action":"close-tab","sessionId":"ralph-b","tabId":"tab-2"}' >/dev/null
sleep 2; T1=$(ntabs ralph-b)
[ "$T1" -lt "$T0" ] 2>/dev/null && ok "close-tab removed a tab ($T0 -> $T1)" || no "close-tab did nothing ($T0 -> $T1)"

[ "$(curlpost /dashboard/action '{"action":"flash","sessionId":"ralph-b"}' | py 'import sys,json;print(json.load(sys.stdin).get("ok"))')" = "True" ] && ok "flash returns ok" || no "flash failed"
[ "$(curlpost /dashboard/action '{"action":"flash-all"}' | py 'import sys,json;print(json.load(sys.stdin).get("ok"))')" = "True" ] && ok "flash-all returns ok" || no "flash-all failed"

curlpost /dashboard/action '{"action":"close-window","sessionId":"ralph-b"}' >/dev/null
sleep 2
[ "$(has ralph-b)" = "no" ] && ok "close-window closed ralph-b" || no "close-window left ralph-b open"

AD browser_close_window '{"sessionId":"ralph-a","reason":"ralph done","takeover":true}' >/dev/null 2>&1
echo "── RESULT: $PASS passed, $FAIL failed ──"
[ "$FAIL" -eq 0 ]
