#!/bin/sh
# tests/run.sh - offline assertion suite for plugin_tetris_3d.
#
# Everything here runs against a throwaway score store, so no real
# ~/.scorpiox/plugins is touched and no network is involved. The gameplay
# assertions drive the HTML UI's own script through node's "npm-free" check when
# a browser is available (tests/e2e.py), and the C side is asserted directly.
#
# 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_tetris_3d"}
[ -x "$BIN" ] || { echo "binary not built: $BIN" >&2; exit 1; }

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

export SX_TETRIS_SCORES="$TMP/scores.json"
unset BOT_PASSWORD

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
}
has() { # has <label> <file> <pattern>
    if grep -qF -- "$3" "$2"; then ok; else bad "$1 (missing: $3)"; fi
}
hasE() { # hasE <label> <file> <regex>
    if grep -qE -- "$3" "$2"; then ok; else bad "$1 (missing regex: $3)"; fi
}
not_has() {
    if grep -qF -- "$3" "$2"; then bad "$1 (found: $3)"; else ok; fi
}

# run <query> [body] -> stdout only (headers stripped)
run() {
    _q="$1"; _b="${2-}"
    if [ -n "$_b" ]; then
        printf '%s' "$_b" | CONTENT_LENGTH=$(printf '%s' "$_b" | wc -c | tr -d ' ') \
            REQUEST_METHOD=POST QUERY_STRING="$_q" "$BIN"
    else
        REQUEST_METHOD=GET QUERY_STRING="$_q" "$BIN"
    fi
}
json() { # json <query> -> last line (JSON body)
    run "$1" | tail -1
}
jget() { # jget <json-string> <python-expression-on-d>
    python3 -c 'import json,sys; d=json.loads(sys.argv[1]); print(eval(sys.argv[2]))' "$1" "$2" 2>/dev/null
}

echo "== metadata"
M=$(REQ=1 "$BIN" --meta)
check "meta name"  "$(jget "$M" 'd["name"]')" "tetris"
check "meta desc"  "$(jget "$M" 'd["desc"]')" "3D block game"
check "meta desc length <= 13" "$(python3 -c 'print(len("3D block game"))')" "13"
M2=$(SX_PLUGIN_META=1 "$BIN")
check "SX_PLUGIN_META equals --meta" "$M2" "$M"
check "meta has exactly two keys" "$(jget "$M" 'sorted(d.keys())')" "['desc', 'name']"
check "--version" "$("$BIN" --version)" "plugin_tetris_3d 1.0.1"
check "--meta needs no auth" "$(BOT_PASSWORD=secret "$BIN" --meta)" "$M"

echo "== score API"
rm -f "$SX_TETRIS_SCORES"
J=$(json 'action=scores')
check "empty store ok"        "$(jget "$J" 'd["ok"]')" "True"
check "empty store highscore" "$(jget "$J" 'd["highscore"]')" "0"
check "empty store list"      "$(jget "$J" 'd["scores"]')" "[]"
check "plugin id"             "$(jget "$J" 'd["plugin"]')" "plugin_tetris_3d"
check "version"               "$(jget "$J" 'd["version"]')" "1.0.1"

J=$(json 'action=save_score&val=1200')
check "save 1200 ok"       "$(jget "$J" 'd["ok"]')" "True"
check "save 1200 high"     "$(jget "$J" 'd["highscore"]')" "1200"
J=$(json 'action=save_score&val=300')
check "lower score kept"   "$(jget "$J" 'd["highscore"]')" "1200"
check "lower score listed" "$(jget "$J" 'd["scores"]')" "[1200, 300]"
J=$(json 'action=save_score&val=9900')
check "higher score wins"  "$(jget "$J" 'd["highscore"]')" "9900"
check "descending order"   "$(jget "$J" 'd["scores"]')" "[9900, 1200, 300]"
J=$(json 'action=save_score&val=600')
check "sorted insert"      "$(jget "$J" 'd["scores"]')" "[9900, 1200, 600, 300]"
J=$(json 'action=save_score&val=0')
check "zero rejected"      "$(jget "$J" 'd["ok"]')" "False"
check "zero error"         "$(jget "$J" 'd["error"]')" "invalid_score"
J=$(json 'action=save_score&val=-5')
check "negative rejected"  "$(jget "$J" 'd["ok"]')" "False"
J=$(json 'action=nonsense')
check "unknown action ok"  "$(jget "$J" 'd["ok"]')" "False"
check "unknown action err" "$(jget "$J" 'd["error"]')" "unknown_action"
J=$(json 'format=json')
check "format=json works"  "$(jget "$J" 'd["ok"]')" "True"
J=$(json 'action=highscore')
check "highscore alias"    "$(jget "$J" 'd["highscore"]')" "9900"
J=$(json 'action=leaderboard')
check "leaderboard alias"  "$(jget "$J" 'd["highscore"]')" "9900"
J=$(json 'action=save_score&val=%31%32%33%34')
check "percent-decoded val" "$(jget "$J" 'd["scores"][0]')" "9900"
check "percent-decoded insert" "$(jget "$J" 'd["scores"]')" "[9900, 1234, 1200, 600, 300]"

echo "== POST body"
J=$(run 'action=save_score' 'val=17777' | tail -1)
check "POST val param" "$(jget "$J" 'd["highscore"]')" "17777"
J=$(run 'action=save_score' 'score=18888' | tail -1)
check "POST score param" "$(jget "$J" 'd["highscore"]')" "18888"
J=$(run 'action=save_score' '19999' | tail -1)
check "POST bare numeric body" "$(jget "$J" 'd["highscore"]')" "19999"
J=$(run '' 'val=24321' | tail -1)
check "POST with no action saves" "$(jget "$J" 'd["highscore"]')" "24321"

echo "== store file"
[ -f "$SX_TETRIS_SCORES" ] && ok || bad "score file was created"
has "file is json" "$SX_TETRIS_SCORES" '"scores"'
check "file has 10 entries cap" "$(python3 -c '
import json,sys
print(len(json.load(open(sys.argv[1]))["scores"])<=10)' "$SX_TETRIS_SCORES")" "True"

echo "== store cap"
rm -f "$SX_TETRIS_SCORES"
i=1
while [ $i -le 14 ]; do
    json "action=save_score&val=$((i * 100))" > /dev/null
    i=$((i + 1))
done
J=$(json 'action=scores')
check "cap keeps 10"    "$(jget "$J" 'len(d["scores"])')" "10"
check "cap keeps best"  "$(jget "$J" 'd["scores"][0]')" "1400"
check "cap drops worst" "$(jget "$J" '400 in d["scores"]')" "False"
check "cap keeps eleventh" "$(jget "$J" '500 in d["scores"]')" "True"

echo "== writability fallback"
SX_TETRIS_SCORES=/proc/definitely/not/writable.json run 'action=save_score&val=123' | tail -1 > "$TMP/unw.json"
check "unwritable store reports error" "$(jget "$(cat "$TMP/unw.json")" 'd["ok"]')" "False"
check "unwritable store error name"    "$(jget "$(cat "$TMP/unw.json")" 'd["error"]')" "score_store_unwritable"

echo "== node auth"
hdr() { head -1 | tr -d '\r'; }
A=$(QUERY_STRING='action=scores' BOT_PASSWORD=testpw "$BIN" | hdr)
check "401 without credentials" "$A" "Status: 401 Unauthorized"
A=$(QUERY_STRING='action=scores&pwd=testpw' BOT_PASSWORD=testpw "$BIN" | tail -1)
check "pwd query accepted" "$(jget "$A" 'd["ok"]')" "True"
A=$(QUERY_STRING='action=scores' BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw "$BIN" | tail -1)
check "X-Bot-Password accepted" "$(jget "$A" 'd["ok"]')" "True"
A=$(QUERY_STRING='action=scores' BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' "$BIN" | tail -1)
check "Bearer accepted" "$(jget "$A" 'd["ok"]')" "True"
A=$(QUERY_STRING='action=scores' BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer wrong' "$BIN" | hdr)
check "wrong Bearer rejected" "$A" "Status: 401 Unauthorized"
A=$(QUERY_STRING='' BOT_PASSWORD=testpw "$BIN" | hdr)
check "html is gated too" "$A" "Status: 401 Unauthorized"
A=$(QUERY_STRING='' BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw "$BIN" | hdr)
check "html served with password" "$A" "Content-Type: text/html; charset=utf-8"

echo "== html"
run 'embed=1' > "$TMP/html.txt"
head -1 "$TMP/html.txt" | grep -q 'Content-Type: text/html' && ok || bad "html content type"
has "html doctype"        "$TMP/html.txt" '<!DOCTYPE html>'
has "html lang"           "$TMP/html.txt" '<html lang="en">'
has "viewport meta"       "$TMP/html.txt" 'width=device-width'
has "canvas element"      "$TMP/html.txt" '<canvas id="cv">'
has "next preview canvas" "$TMP/html.txt" 'id="cvNext"'
has "hold canvas"         "$TMP/html.txt" 'id="cvHold"'
has "score element"       "$TMP/html.txt" 'id="vScore"'
has "best element"        "$TMP/html.txt" 'id="vBest"'
has "lines element"       "$TMP/html.txt" 'id="vLines"'
has "overlay"             "$TMP/html.txt" 'id="overlay"'
has "theme toggle"        "$TMP/html.txt" 'id="btnTheme"'
has "dark media query"    "$TMP/html.txt" 'prefers-color-scheme'
has "explicit dark theme" "$TMP/html.txt" 'data-theme="dark"'
has "explicit light theme" "$TMP/html.txt" 'data-theme="light"'
has "theme reads ?theme="      "$TMP/html.txt" 'theme=(light|dark)'
has "theme listens sx-theme"   "$TMP/html.txt" "d.type==='sx-theme'"
has "theme asks the host"      "$TMP/html.txt" "sx-theme-request"
has "bot token --bg-card"      "$TMP/html.txt" '--bg-card'
has "bot token --surface-2"    "$TMP/html.txt" '--surface-2'
had_toggle_embed=$(grep -c 'html.embedded #btnTheme' "$TMP/html.txt")
check "toggle hidden when embedded ($had_toggle_embed)" "$had_toggle_embed" "1"
not_has "no private palette 08080b" "$TMP/html.txt" '08080b'
not_has "no private palette eceef3" "$TMP/html.txt" 'eceef3'
not_has "no retired brand casing" "$TMP/html.txt" 'Scorpio'"X Bot"
has "touch controls pad"  "$TMP/html.txt" 'id="pad"'
has "left button"         "$TMP/html.txt" 'id="bLeft"'
has "rotate button"       "$TMP/html.txt" 'id="bRot"'
has "hard drop button"    "$TMP/html.txt" 'id="bDrop"'
has "hold button"         "$TMP/html.txt" 'id="bHold"'
has "pause button"        "$TMP/html.txt" 'id="bPause"'
has "ghost piece calc"    "$TMP/html.txt" 'function ghostY'
has "hold queue logic"    "$TMP/html.txt" 'function hold'
has "next queue refill"   "$TMP/html.txt" 'function refill'
has "3d projector"        "$TMP/html.txt" 'function project'
has "cage rendering"      "$TMP/html.txt" 'function drawCage'
has "seven tetrominoes"   "$TMP/html.txt" "k:'I'"
has "Z piece"             "$TMP/html.txt" "k:'Z'"
has "keyboard handler"    "$TMP/html.txt" "addEventListener('keydown'"
has "pointer handler"     "$TMP/html.txt" "addEventListener('pointerup'"
has "requestAnimationFrame" "$TMP/html.txt" 'requestAnimationFrame(loop)'
has "level speed curve"   "$TMP/html.txt" 'dropInterval = Math.max(90'
has "line clear scoring"  "$TMP/html.txt" 'var table = [0, 100, 300, 500, 800]'
has "mobile breakpoint"   "$TMP/html.txt" '@media (max-width:420px)'
has "short viewport rule" "$TMP/html.txt" '@media (max-height:560px)'
has "hub proxy route"     "$TMP/html.txt" "/plugins?plugin="
has "direct plugin route" "$TMP/html.txt" "/plugin_tetris_3d?action="
has "pwd bootstrap"       "$TMP/html.txt" 'bot_active_pwd'
has "pwd header"          "$TMP/html.txt" 'X-Bot-Password'
not_has "no Content-Length" "$TMP/html.txt" 'Content-Length'
not_has "no external script" "$TMP/html.txt" '<script src='
not_has "no CDN"          "$TMP/html.txt" 'cdnjs'
not_has "no three.js"     "$TMP/html.txt" 'three.min.js'
not_has "no emoji speaker" "$TMP/html.txt" '&#x1F50A;'
check "html is substantial" "$(python3 -c 'import sys,os; print(os.path.getsize(sys.argv[1])>20000)' "$TMP/html.txt")" "True"

echo "== emoji / control-char audit on source and UI"
python3 - "$ROOT" <<'PY'
import os, sys, unicodedata
root = sys.argv[1]
bad = []
for base, dirs, files in os.walk(root):
    dirs[:] = [d for d in dirs if d not in ('.git', '__pycache__', 'bin')]
    for f in files:
        if not f.endswith(('.c', '.h', '.sh', '.md', '.ps1', '.json', '.py')):
            continue
        p = os.path.join(base, f)
        try:
            t = open(p, encoding='utf-8').read()
        except Exception:
            continue
        for ch in t:
            o = ord(ch)
            if o > 0x2100 and unicodedata.category(ch).startswith('S'):
                bad.append((p, hex(o)))
print('EMOJI_HITS=%d' % len(bad))
for p, o in bad[:5]:
    print('  %s %s' % (p, o))
PY
check "zero emoji in sources" "$(python3 - "$ROOT" <<'PY'
import os, sys, unicodedata
root = sys.argv[1]
n = 0
for base, dirs, files in os.walk(root):
    dirs[:] = [d for d in dirs if d not in ('.git', '__pycache__', 'bin')]
    for f in files:
        if not f.endswith(('.c', '.h', '.sh', '.md', '.ps1', '.json', '.py')):
            continue
        try:
            t = open(os.path.join(base, f), encoding='utf-8').read()
        except Exception:
            continue
        n += sum(1 for ch in t if ord(ch) > 0x2100 and unicodedata.category(ch).startswith('S'))
print(n)
PY
)" "0"

echo "== secret & private-address audit (full git history)"
SCAN="$TMP/history.txt"
git -C "$ROOT" log -p --all 2>/dev/null \
  | grep -v '^Author: ' \
  | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '" > "$SCAN" || : > "$SCAN"
hits() { grep -Eo "$1" "$SCAN" 2>/dev/null | sort -u | wc -l | tr -d ' '; }
check "no GitHub token"        "$(hits 'ghp_[A-Za-z0-9]{20,}')" "0"
check "no HuggingFace token"   "$(hits 'hf_[A-Za-z0-9]{20,}')" "0"
check "no scorpiox-git token"  "$(hits '3ef2c00cb68e')" "0"
check "no password literal"    "$(hits 'Xboxone'09'0'9'')" "0"
check "no runner pass"         "$(hits 'RUNNER_'"'"'PASS=')" "0"
check "no private 192.168 net" "$(hits '192\.168\.[0-9]{1,3}\.')" "0"
check "no private 10.0 net"    "$(hits '(^|[^0-9])10\.0\.[0-9]{1,3}\.')" "0"
check "no private 172.16 net"  "$(hits '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]{1,3}\.')" "0"
check "no internal hostnames"  "$(hits 'INTERNAL_HOST_A|INTERNAL_HOST_B|INTERNAL_HOST_C')" "0"

echo "== worktree hygiene"
not_has "no Content-Length in C source" "$ROOT/src/plugin_tetris_3d.c" 'Content-Length'
has "stdin guarded by CONTENT_LENGTH" "$ROOT/src/plugin_tetris_3d.c" 'CONTENT_LENGTH'
has "require_node_auth present"       "$ROOT/src/plugin_tetris_3d.c" 'require_node_auth'
has "three credential forms: query"   "$ROOT/src/plugin_tetris_3d.c" 'get_query_val(qs, "pwd"'
has "three credential forms: header"  "$ROOT/src/plugin_tetris_3d.c" 'HTTP_X_BOT_PASSWORD'
has "three credential forms: bearer"  "$ROOT/src/plugin_tetris_3d.c" 'Bearer '
has "win32 branch present"            "$ROOT/src/plugin_tetris_3d.c" 'defined(_WIN32)'
has "darwin branch present"           "$ROOT/src/plugin_tetris_3d.c" '__APPLE__'
has "license file is MIT"             "$ROOT/LICENSE" 'MIT License'

echo "== cross-build artifacts"
if [ -f "$ROOT/plugin_tetris_3d.exe" ]; then
    check "windows artifact is PE" "$(head -c 2 "$ROOT/plugin_tetris_3d.exe")" "MZ"
else
    echo "  skip windows PE check (not built here)"
fi
if [ -f "$ROOT/plugin_tetris_3d.musl" ]; then
    head -c 4 "$ROOT/plugin_tetris_3d.musl" | od -An -c | grep -q '177   E   L   F' && ok || bad "musl artifact is ELF"
    if grep -qi 'GNU/Linux' "$ROOT/plugin_tetris_3d.musl" 2>/dev/null; then
        bad "musl artifact still references glibc"
    else
        ok
    fi
else
    echo "  skip musl ELF check (not built here)"
fi
if [ -f "$ROOT/plugin_tetris_3d.arm64" ]; then
    file "$ROOT/plugin_tetris_3d.arm64" 2>/dev/null | grep -q 'ARM aarch64' && ok || bad "arm64 artifact is aarch64"
else
    echo "  skip arm64 check (not built here)"
fi

echo "== browser viewport & console (optional)"
if [ -x "$ROOT/plugin_tetris_3d" ] && python3 -c 'import playwright' >/dev/null 2>&1; then
    python3 "$ROOT/tests/e2e.py" && ok || bad "playwright e2e"
else
    echo "  skip playwright (not installed)"
fi

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