#!/bin/sh
# tests/run.sh - offline assertion suite for plugin_sessionstats.
#
# Everything here runs against synthetic session fixtures in a throwaway
# directory, so no real ~/.scorpiox/sessions is touched and no network, shell
# tool or real clock is involved. Every timestamp is fixed, so the expected
# durations are exact.
#
# Usage: sh tests/run.sh [path-to-binary]
# Exit: 0 when every assertion passes.

set -u

ROOT=$(cd "$(dirname "$0")/.." && pwd)
BIN=${1:-"$ROOT/plugin_sessionstats"}
[ -x "$BIN" ] || { echo "binary not built: $BIN" >&2; exit 1; }

TMP=$(mktemp -d "${TMPDIR:-/tmp}/sx_sessionstats_XXXXXX")
trap 'rm -rf "$TMP"' EXIT

PASS=0
FAIL=0
ok()   { PASS=$((PASS+1)); }
bad()  { FAIL=$((FAIL+1)); printf '  FAIL  %s\n' "$1"; }
check() { # check <label> <actual> <expected>
    if [ "$2" = "$3" ]; then ok; else bad "$1 (got '$2', want '$3')"; fi
}

# ---------------------------------------------------------------- fixtures
S="$TMP/sessions"
mkdir -p "$S/s1" "$S/s2" "$S/s3"

# --- s1: two complete runs, three tool kinds, a profile and a model
cat > "$S/s1/meta.json" <<'EOF'
{
  "id": "2026_01_01_quiet_curie",
  "thread_guid": "11111111-2222-3333-4444-555555555555",
  "start_time": "2026-01-01 10:00:00",
  "start_epoch": 1767261600,
  "model": "alpha-1",
  "provider": "openai",
  "profile": "profile-alpha",
  "cwd": "/work/alpha"
}
EOF
cat > "$S/s1/stats.json" <<'EOF'
{
  "model": "alpha-1",
  "branch": "main",
  "input_tokens": 1000,
  "output_tokens": 250,
  "cache_read_tokens": 800,
  "cache_creation_tokens": 50
}
EOF
cat > "$S/s1/events.jsonl" <<'EOF'
{"ts":"2026-01-01 10:00:00","event":"session_start","model":"alpha-1","provider":"openai","profile":"profile-alpha"}
{"ts":"2026-01-01 10:00:05","event":"user_message","len":10}
{"ts":"2026-01-01 10:00:05","event":"agent_run_start","msg_len":10}
{"ts":"2026-01-01 10:00:15","event":"tool_use","tool":"Bash","input_len":12}
{"ts":"2026-01-01 10:00:20","event":"tool_use","tool":"Bash","input_len":20}
{"ts":"2026-01-01 10:00:30","event":"tool_use","tool":"Read","input_len":5}
{"ts":"2026-01-01 10:00:35","event":"agent_idle"}
{"ts":"2026-01-01 10:05:00","event":"user_message","len":8}
{"ts":"2026-01-01 10:05:00","event":"agent_run_start","msg_len":8}
{"ts":"2026-01-01 10:05:25","event":"tool_use","tool":"Write","input_len":9}
{"ts":"2026-01-01 10:05:40","event":"agent_complete"}
EOF
# run 1 = 10:00:05 -> 10:00:35 = 30s; run 2 = 10:05:00 -> 10:05:40 = 40s
# active = 70s, wall = 10:00:00 -> 10:05:40 = 340s, idle = 270s

# --- s2: still running (open run + thinking marker), different profile
cat > "$S/s2/meta.json" <<'EOF'
{
  "id": "2026_01_02_bold_lovelace",
  "start_time": "2026-01-02 08:00:00",
  "model": "beta-2",
  "provider": "anthropic",
  "profile": "profile-beta",
  "cwd": "/work/beta"
}
EOF
cat > "$S/s2/events.jsonl" <<'EOF'
{"ts":"2026-01-02 08:00:00","event":"session_start","model":"beta-2","provider":"anthropic","profile":"profile-beta"}
{"ts":"2026-01-02 08:00:10","event":"user_message","len":5}
{"ts":"2026-01-02 08:00:10","event":"agent_run_start","msg_len":5}
{"ts":"2026-01-02 08:01:00","event":"tool_use","tool":"Bash","input_len":7}
{"ts":"2026-01-02 08:01:10","event":"api_response","turn":1}
EOF
: > "$S/s2/thinking"
# run still open at last event: active = 08:00:10 -> 08:01:10 = 60s, wall = 70s

# --- s3: metadata only, no events at all (degenerate but must not crash)
cat > "$S/s3/meta.json" <<'EOF'
{
  "id": "2026_01_03_empty_nash",
  "start_time": "2026-01-03 00:00:00",
  "start_epoch": 1767398400
}
EOF

run() { # run <query-string> [extra env assignments via args 2..]
    qs="$1"; shift
    env SX_SESSIONS_DIR="$S" QUERY_STRING="$qs" "$@" "$BIN" 2>/dev/null
}

jsoncheck() { # jsoncheck <label> <json-file> <python-expression on d> <expected>
    label="$1"; file="$2"; expr="$3"; want="$4"
    got=$(python3 - "$file" "$expr" <<'PY'
import json, sys
d = json.load(open(sys.argv[1]))
try:
    v = eval(sys.argv[2], {"d": d, "len": len, "sum": sum, "sorted": sorted})
except Exception as e:
    v = "ERR:%s" % e
print(v)
PY
)
    check "$label" "$got" "$want"
}

echo "== meta mode"
out=$("$BIN" --meta)
check "--meta exact JSON" "$out" '{"name":"sessions","desc":"Turn metrics"}'
out=$(SX_PLUGIN_META=1 "$BIN")
check "SX_PLUGIN_META=1 exact JSON" "$out" '{"name":"sessions","desc":"Turn metrics"}'
check "meta name is other field free" "$(printf '%s' "$out" | python3 -c 'import json,sys;d=json.load(sys.stdin);print(len(d))')" "2"
check "meta name length <= 2 words" "$(printf '%s' "$out" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)["name"].split()))')" "1"
check "meta desc length <= 15" "$(printf '%s' "$out" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)["desc"])<=15)')" "True"

echo "== auth gate"
code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | tr -d '\r')
check "401 without credential" "$code" "Status: 401 Unauthorized"
code=$(BOT_PASSWORD=pw HTTP_X_BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | cut -c1-12)
check "header credential accepted" "$code" "Content-Type"
code=$(BOT_PASSWORD=pw HTTP_AUTHORIZATION="Bearer pw" SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | cut -c1-12)
check "bearer credential accepted" "$code" "Content-Type"
code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING='action=summary&pwd=pw' "$BIN" | head -1 | cut -c1-12)
check "query credential accepted" "$code" "Content-Type"
code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" "$BIN" --meta | cut -c1-10)
check "--meta stays unauthenticated" "$code" '{"name":"s'
code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | tail -1)
check "401 body is JSON error" "$code" '{"ok":false,"error":"invalid node password"}'

echo "== summary shape"
run 'action=summary' > "$TMP/sum.json"
last=$(tail -1 "$TMP/sum.json")
check "summary has no Content-Length" "$(printf '%s' "$last" | grep -c 'Content-Length')" "0"
printf '%s' "$last" > "$TMP/sum.body.json"
jsoncheck "ok"           "$TMP/sum.body.json" 'd["ok"]' "True"
jsoncheck "plugin id"    "$TMP/sum.body.json" 'd["plugin"]' "plugin_sessionstats"
jsoncheck "version"      "$TMP/sum.body.json" 'd["version"]' "1.0.1"
jsoncheck "root_found"   "$TMP/sum.body.json" 'd["root_found"]' "True"
jsoncheck "session count" "$TMP/sum.body.json" 'd["count"]' "3"
jsoncheck "active_now"    "$TMP/sum.body.json" 'd["active_now"]' "1"
jsoncheck "turns total"   "$TMP/sum.body.json" 'd["turns"]' "3"
jsoncheck "tool events"   "$TMP/sum.body.json" 'd["tool_events"]' "5"
jsoncheck "total sec"     "$TMP/sum.body.json" 'd["total_sec"]' "410"
jsoncheck "active sec"    "$TMP/sum.body.json" 'd["active_sec"]' "130"
jsoncheck "idle sec"      "$TMP/sum.body.json" 'd["idle_sec"]' "280"
jsoncheck "idle+active=total" "$TMP/sum.body.json" 'd["idle_sec"]+d["active_sec"]==d["total_sec"]' "True"
jsoncheck "duty pct"      "$TMP/sum.body.json" 'round(d["duty_cycle_pct"],2)' "31.71"
jsoncheck "total_fmt"     "$TMP/sum.body.json" 'd["total_fmt"]' "06m 50s"
jsoncheck "active_fmt"    "$TMP/sum.body.json" 'd["active_fmt"]' "02m 10s"
jsoncheck "idle_fmt"      "$TMP/sum.body.json" 'd["idle_fmt"]' "04m 40s"
jsoncheck "sessions array length" "$TMP/sum.body.json" 'len(d["sessions"])' "3"
jsoncheck "profiles present"  "$TMP/sum.body.json" 'len(d["profiles"])' "3"
jsoncheck "models present"    "$TMP/sum.body.json" 'len(d["models"])' "3"
jsoncheck "profile alpha leads" "$TMP/sum.body.json" 'd["profiles"][0]["profile"]' "profile-alpha"
jsoncheck "profile alpha active" "$TMP/sum.body.json" 'd["profiles"][0]["active_sec"]' "70"
jsoncheck "profile beta active"  "$TMP/sum.body.json" 'd["profiles"][1]["active_sec"]' "60"
jsoncheck "profile alpha sessions" "$TMP/sum.body.json" 'd["profiles"][0]["sessions"]' "1"
jsoncheck "unknown profile bucket" "$TMP/sum.body.json" 'd["profiles"][2]["profile"]' "unknown"
jsoncheck "model alpha leads"  "$TMP/sum.body.json" 'd["models"][0]["model"]' "alpha-1"

echo "== summary is sorted newest first"
jsoncheck "first session is s2" "$TMP/sum.body.json" 'd["sessions"][0]["id"]' "2026_01_02_bold_lovelace"
jsoncheck "second session is s1" "$TMP/sum.body.json" 'd["sessions"][1]["id"]' "2026_01_01_quiet_curie"

echo "== per-session numbers (s1)"
cat > "$TMP/py_s1.py" <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
for s in d["sessions"]:
    if s["dir"]=="s1":
        print(s["total_sec"], s["active_sec"], s["idle_sec"], s["turns"],
              s["duty_cycle_pct"], s["model"], s["profile"], s["branch"],
              s["tokens"]["in"], s["tokens"]["out"], s["tokens"]["cache_read"],
              s["tokens"]["cache_write"])
PY
got=$(python3 "$TMP/py_s1.py" "$TMP/sum.body.json")
check "s1 numbers" "$got" "340 70 270 2 20.59 alpha-1 profile-alpha main 1000 250 800 50"

cat > "$TMP/py_s1tools.py" <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
for s in d["sessions"]:
    if s["dir"]=="s1":
        print(" ".join("%s=%d"%(t["name"],t["calls"]) for t in s["tools"]))
PY
got=$(python3 "$TMP/py_s1tools.py" "$TMP/sum.body.json")
check "s1 tools sorted by calls" "$got" "Bash=2 Read=1 Write=1"

cat > "$TMP/py_s1id.py" <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
for s in d["sessions"]:
    if s["dir"]=="s1":
        print(s["id"], s["start_time"], s["is_active"], s["avg_turn_sec"])
PY
got=$(python3 "$TMP/py_s1id.py" "$TMP/sum.body.json")
check "s1 identity fields" "$got" "2026_01_01_quiet_curie 2026-01-01 10:00:00 False 35.0"

echo "== per-session numbers (s2, still running)"
cat > "$TMP/py_s2.py" <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
for s in d["sessions"]:
    if s["dir"]=="s2":
        print(s["total_sec"], s["active_sec"], s["idle_sec"], s["turns"], s["is_active"])
PY
got=$(python3 "$TMP/py_s2.py" "$TMP/sum.body.json")
check "s2 numbers" "$got" "70 60 10 1 True"

echo "== degenerate session (metadata only)"
cat > "$TMP/py_s3.py" <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
for s in d["sessions"]:
    if s["dir"]=="s3":
        print(s["total_sec"], s["active_sec"], s["turns"], s["is_active"])
PY
got=$(python3 "$TMP/py_s3.py" "$TMP/sum.body.json")
check "s3 numbers" "$got" "0 0 0 False"

echo "== action=session"
run 'action=session&sid=s1' | tail -1 > "$TMP/one.json"
jsoncheck "session ok"     "$TMP/one.json" 'd["ok"]' "True"
jsoncheck "session id"     "$TMP/one.json" 'd["session"]["id"]' "2026_01_01_quiet_curie"
jsoncheck "session active" "$TMP/one.json" 'd["session"]["active_sec"]' "70"
jsoncheck "session tools"  "$TMP/one.json" 'len(d["session"]["tools"])' "3"
jsoncheck "session summary block" "$TMP/one.json" 'd["summary"]["turns"]' "2"
run 'action=session&sid=2026_01_02_bold_lovelace' | tail -1 > "$TMP/one2.json"
jsoncheck "session by full id" "$TMP/one2.json" 'd["session"]["dir"]' "s2"
run 'action=session&sid=nope' | tail -1 > "$TMP/one3.json"
jsoncheck "unknown session ok=false" "$TMP/one3.json" 'd["ok"]' "False"
jsoncheck "unknown session error"    "$TMP/one3.json" 'd["error"]' "session not found"
run 'action=session' | tail -1 > "$TMP/one4.json"
jsoncheck "missing sid error" "$TMP/one4.json" 'd["error"]' "missing sid parameter"
run 'action=session&id=s1' | tail -1 > "$TMP/one5.json"
jsoncheck "id= alias accepted" "$TMP/one5.json" 'd["session"]["dir"]' "s1"
run 'action=session&sid=%73%31' | tail -1 > "$TMP/one6.json"
jsoncheck "percent-decoded sid" "$TMP/one6.json" 'd["session"]["dir"]' "s1"

echo "== format=json"
run 'format=json' | tail -1 > "$TMP/fmt.json"
jsoncheck "format=json returns summary" "$TMP/fmt.json" 'd["count"]' "3"
jsoncheck "format=json ok"             "$TMP/fmt.json" 'd["ok"]' "True"

echo "== unknown action falls back to the summary"
run 'action=whatever' | tail -1 > "$TMP/unk.json"
jsoncheck "unknown action still JSON" "$TMP/unk.json" 'd["ok"]' "True"

echo "== html"
run 'embed=1' > "$TMP/html.txt"
head -1 "$TMP/html.txt" | grep -q 'Content-Type: text/html' && ok || bad "html content type"
grep -q '<!DOCTYPE html>' "$TMP/html.txt" && ok || bad "html doctype"
grep -q 'Session Analytics' "$TMP/html.txt" && ok || bad "html title"
grep -q "id='kSessions'" "$TMP/html.txt" && ok || bad "kpi card sessions"
grep -q "id='railOn'" "$TMP/html.txt" && ok || bad "active rail"
grep -q "id='profBars'" "$TMP/html.txt" && ok || bad "profile bars"
grep -q "id='modelBars'" "$TMP/html.txt" && ok || bad "model bars"
grep -q "id='tbody'" "$TMP/html.txt" && ok || bad "session table"
grep -q "btnTheme" "$TMP/html.txt" && ok || bad "theme toggle"
grep -q "prefers-color-scheme" "$TMP/html.txt" && ok || bad "dark/light support"
grep -q 'theme=(light|dark)' "$TMP/html.txt" && ok || bad "theme: reads ?theme= before paint"
grep -q "d.type==='sx-theme'" "$TMP/html.txt" && ok || bad "theme: listens for sx-theme"
grep -q "sx-theme-request" "$TMP/html.txt" && ok || bad "theme: asks the host for the theme"
grep -q -- "--bg-card" "$TMP/html.txt" && ok || bad "theme: bot token --bg-card"
grep -q -- "--surface-2" "$TMP/html.txt" && ok || bad "theme: bot token --surface-2"
grep -q -- "--text-2" "$TMP/html.txt" && ok || bad "theme: bot token --text-2"
grep -q "embed-hide" "$TMP/html.txt" && ok || bad "theme: toggle hidden when embedded"
grep -q 'Scorpio'"X Bot" "$TMP/html.txt" && bad "theme: no retired brand casing" || ok
grep -q "0d0d0f" "$TMP/html.txt" && bad "theme: no private palette 0d0d0f" || ok
grep -q "18181b" "$TMP/html.txt" && bad "theme: no private palette 18181b" || ok
grep -q "max-width:400px" "$TMP/html.txt" && ok || bad "narrow breakpoint"
grep -q "plugin_sessionstats?action=" "$TMP/html.txt" && ok || bad "direct plugin route"
grep -q "plugins?plugin=" "$TMP/html.txt" && ok || bad "hub proxy route"
grep -q "bot_active_pwd" "$TMP/html.txt" && ok || bad "pwd bootstrap"
grep -q "X-Bot-Password" "$TMP/html.txt" && ok || bad "pwd header"
grep -qi 'content-length' "$TMP/html.txt" && bad "html must not emit Content-Length" || ok

echo "== initial id is injected and escaped"
run 'id=s1' > "$TMP/html2.txt"
grep -q "q.get('id')||'s1'" "$TMP/html2.txt" && ok || bad "initial id injected"
mkdir -p "$S/bad'name"
run "id=x%27y" > "$TMP/html3.txt"
grep -q "q.get('id')||'x\\\\'y'" "$TMP/html3.txt" && ok || bad "single quote escaped in initial id"
rm -rf "$S/bad'name"

echo "== missing sessions root"
out=$(SX_SESSIONS_DIR="$TMP/does-not-exist" QUERY_STRING='action=summary' "$BIN" | tail -1)
printf '%s' "$out" > "$TMP/noroot.json"
jsoncheck "root_found false"   "$TMP/noroot.json" 'd["root_found"]' "False"
jsoncheck "empty summary ok"   "$TMP/noroot.json" 'd["ok"]' "True"
jsoncheck "zero sessions"      "$TMP/noroot.json" 'd["count"]' "0"
jsoncheck "empty profiles"     "$TMP/noroot.json" 'd["profiles"]' "[]"

echo "== the root must be a directory, not any openable path"
: > "$TMP/notadir"
out=$(SX_SESSIONS_DIR="$TMP/notadir" QUERY_STRING='action=summary' "$BIN" | tail -1)
printf '%s' "$out" > "$TMP/notadir.json"
jsoncheck "file root rejected" "$TMP/notadir.json" 'd["root_found"]' "False"

echo "== read-only guarantee"
before=$(find "$S" -type f | wc -l | tr -d ' ')
run 'action=summary' >/dev/null
run 'action=session&sid=s1' >/dev/null
run 'embed=1' >/dev/null
after=$(find "$S" -type f | wc -l | tr -d ' ')
check "no files created" "$after" "$before"
diff -r "$S" "$S" >/dev/null 2>&1 && ok || bad "fixture tree unchanged"

echo "== no emoji anywhere in the source"
if grep -qP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' "$ROOT/src/plugin_sessionstats.c" 2>/dev/null; then
    bad "source contains emoji"
else
    ok
fi

echo "== no private addresses or credentials in the whole history"
HIST="$TMP/history.txt"
git -C "$ROOT" log -p --all 2>/dev/null \
  | grep -v '^Author: ' \
  | grep -vE 'scan "|audit "|HITS=|grep -E|P_ROOT=|P_WT=|PK="' > "$HIST" || : > "$HIST"
check "no 192.168 in history" "$(grep -Eco '192\.168\.[0-9]+\.[0-9]+' "$HIST" || true)" "0"
check "no 10.x private range" "$(grep -Eco '(^|[^0-9.])10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' "$HIST" || true)" "0"
check "no 172.16-31 range"    "$(grep -Eco '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' "$HIST" || true)" "0"
check "no ghp_ token"         "$(grep -Eco 'ghp_[A-Za-z0-9]{20,}' "$HIST" || true)" "0"
check "no hf_ token"          "$(grep -Eco 'hf_[A-Za-z0-9]{20,}' "$HIST" || true)" "0"
check "no internal hostnames" "$(grep -Eco 'intel-ultra'"2"'|INTERNAL_HOST_B|INTERNAL_HOST_C' "$HIST" || true)" "0"
check "no default password"   "$(grep -Eco 'Xboxone'0909'|TESTPW' "$HIST" || true)" "0"

echo "== Windows artifact shape (when the cross build exists)"
if [ -f "$ROOT/plugin_sessionstats.exe" ]; then
    check "windows artifact starts with MZ" "$(head -c 2 "$ROOT/plugin_sessionstats.exe")" "MZ"
else
    echo "  skip (plugin_sessionstats.exe not built)"
fi

echo "== musl artifact shape (when the static build exists)"
if [ -f "$ROOT/plugin_sessionstats.musl" ]; then
    check "musl artifact is a static ELF" "$(head -c 4 "$ROOT/plugin_sessionstats.musl" | od -An -c | tr -d ' \n')" '177ELF'
else
    echo "  skip (plugin_sessionstats.musl not built)"
fi

echo
printf '  %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ] || exit 1
