#!/bin/sh
# tests/run.sh - offline checks for plugin_antigravity_login across all 3 modes.
#
# Every check runs against ./plugin_antigravity_login with the credential paths
# and both CLIs redirected at throwaway fixtures, so the suite proves the public
# contract without touching a real Google session and without a network.
#
# What it proves:
#   - --meta is exactly {"name":"google","desc":"Google login"} and is reachable
#     with no password (discovery must never be gated)
#   - every action 401s without the node password, and 401 is a real CGI Status
#   - status parses the accounts array + sibling files + the CLI JSON and never
#     emits a token
#   - start returns the CLI's auth_url, finish rejects garbage codes locally and
#     re-reads state after a successful exchange
#   - refresh performs the grant, drops the access token, and surfaces failure
#   - the HTML page carries the bot theme handoff, no CDN and no <script src=>
#   - the source has no hard-coded secret, no internal address and no emoji
#
# Exit code 0 = everything passed.

set -u

ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT" || exit 1

BIN=./plugin_antigravity_login
ID=plugin_antigravity_login
PASS=0
FAIL=0

if [ -t 1 ]; then
    C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
else
    C_OK=; C_BAD=; C_B=; C_0=
fi
pass() { PASS=$((PASS + 1)); printf '  %sok%s   %s\n' "$C_OK" "$C_0" "$1"; }
fail() { FAIL=$((FAIL + 1)); printf '  %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }

check() { # check <desc> <expected-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
        fail "$1 (want: $2)"; printf '       got: %s\n' "$(printf '%s' "$3" | head -c 400)"
    fi
}

check_not() { # check_not <desc> <forbidden-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then
        fail "$1 (must NOT contain: $2)"; else pass "$1"
    fi
}

section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }

# strip CGI headers if present, drop CRs, keep the payload
body() {
    printf '%s\n' "$1" | tr -d '\r' | awk '
        BEGIN { inhdr = 0 }
        NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next }
        inhdr && $0 == "" { inhdr = 0; next }
        inhdr { next }
        { print }
    '
}

json_ok() { # json_ok <desc> <json> [python-expression]
    expr=${3:-True}
    if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then
        pass "$1"
    else
        fail "$1 (invalid JSON or assertion failed)"; printf '       got: %s\n' "$(printf '%s' "$2" | head -c 400)"
    fi
}

api() { body "$(QUERY_STRING="$1" $BIN)"; }
apiraw() { QUERY_STRING="$1" $BIN; }

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    gcc -O2 -std=c99 -Wall -Wextra -I src -o "$BIN" src/plugin_antigravity_login.c || {
        fail "native build"; exit 1; }
fi
pass "native binary present"

# generated page header must match src/ui.html
if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
    pass "src/ui_html.h is in sync with src/ui.html"
else
    fail "src/ui_html.h is stale - run tools/gen_ui.py"
fi

# the page header must not be hand-edited: it is generated from ui.html
check "ui header is marked generated" \
      "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"

# ---------------------------------------------------------------- fixtures
FIX=$(mktemp -d 2>/dev/null || mktemp -d -t agyfix)
trap 'rm -rf "$FIX"' EXIT

mkdir -p "$FIX/none" "$FIX/empty" "$FIX/full" "$FIX/full/scorpiox-env" "$FIX/pending"
export ANTIGRAVITY_LOGIN_BIN="$ROOT/tests/mock_login.sh"
export ANTIGRAVITY_TOKEN_BIN="$ROOT/tests/mock_token.sh"
export ANTIGRAVITY_PENDING_PATH="$FIX/pending/antigravity-default.json"

# empty credentials file (exists but has no accounts)
: > "$FIX/empty/antigravity_accounts.json"

# a realistic signed-in fixture: the accounts array + selected account + profile
cat > "$FIX/full/antigravity_accounts.json" <<'JSON'
[
  {"email":"other@example.com","refresh_token":"1//other-refresh"},
  {"email":"pico@example.com","refresh_token":"1//pico-refresh-value"}
]
JSON
printf 'pico@example.com\n' > "$FIX/full/selected_account.txt"
printf 'PROVIDER=google_gemini\nGOOGLE_TOKEN_SOURCE=local\nGOOGLE_ACCOUNT=pico@example.com\nGOOGLE_PROJECT_ID=proj-mock-42\nMODEL=gemini-3.7-flash-tiered\n' \
    > "$FIX/full/scorpiox-env/antigravity.txt"

# ---------------------------------------------------------------- metadata
section "mode 1: discovery metadata"
META=$("$BIN" --meta)
if [ "$META" = '{"name":"google","desc":"Google login"}' ]; then
    pass "--meta is exactly the contract line"
else
    fail "--meta mismatch"; printf '       got: %s\n' "$META"
fi
json_ok "--meta is valid JSON with name+desc" "$META" \
        "d['name']=='google' and d['desc']=='Google login'"
check "--meta desc is within 15 chars" "Google login" "$META"

ENVMETA=$(SX_PLUGIN_META=1 "$BIN")
check "SX_PLUGIN_META=1 works like --meta" '"name":"google"' "$ENVMETA"

# --meta must not be gated by the node password
META_PW=$(BOT_PASSWORD=testpw "$BIN" --meta)
check "--meta ignores BOT_PASSWORD" '"name":"google"' "$META_PW"

check "--version prints the plugin id and version" "$ID" "$("$BIN" --version)"

# ---------------------------------------------------------------- auth
section "node auth"
export BOT_PASSWORD=testpw
RAW=$(apiraw "action=status")
check "unauthenticated action returns a 401 Status line" "Status: 401 Unauthorized" "$RAW"
check "unauthenticated action body is JSON" '"error":"invalid node password"' "$RAW"

RAW=$(apiraw "")
check "unauthenticated HTML also 401s" "Status: 401 Unauthorized" "$RAW"

HDR=$(api "action=status&pwd=testpw")
check "?pwd= authenticates" '"ok":true' "$HDR"

HDR=$(QUERY_STRING="action=status" HTTP_X_BOT_PASSWORD=testpw $BIN)
check "X-Bot-Password authenticates" '"ok":true' "$(body "$HDR")"

HDR=$(QUERY_STRING="action=status" HTTP_AUTHORIZATION="Bearer testpw" $BIN)
check "Authorization: Bearer authenticates" '"ok":true' "$(body "$HDR")"

WRONG=$(apiraw "action=status&pwd=nope")
check "a wrong password still 401s" "Status: 401 Unauthorized" "$WRONG"
unset BOT_PASSWORD

# ---------------------------------------------------------------- status
section "action=status"
NOFIX=$(ANTIGRAVITY_CREDS_PATH="$FIX/none/antigravity_accounts.json" \
        MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":false,"expires_at":0,"expired":false,"has_refresh":false,"pending":false}' \
        api "action=status")
json_ok "status with no credentials is valid JSON" "$NOFIX" \
        "d['ok'] is True and d['logged_in'] is False and d['has_refresh'] is False"
check_not "status with no credentials emits no token field" "refresh_token" "$NOFIX"

EMPTYJ=$(ANTIGRAVITY_CREDS_PATH="$FIX/empty/antigravity_accounts.json" api "action=status")
json_ok "empty accounts file yields logged_in false" "$EMPTYJ" \
        "d['ok'] is True and d['logged_in'] is False"

FULL=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
       MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":true,"expires_at":4102444800000,"expired":false,"has_refresh":true,"pending":false,"identity":"pico@example.com"}' \
       api "action=status")
json_ok "signed-in status reports logged_in + has_refresh" "$FULL" \
        "d['ok'] is True and d['logged_in'] is True and d['has_refresh'] is True"
check_not "signed-in status never returns the refresh token" "1//pico-refresh-value" "$FULL"
check_not "signed-in status never returns any token literal" "refresh_token\":" "$FULL"

check "status reports the selected account email" "pico@example.com" "$FULL"
check "status reads the companion project from the profile" "proj-mock-42" "$FULL"
check "status reports the credentials path" "$FIX/full/antigravity_accounts.json" "$FULL"
json_ok "status has the full contract field set" "$FULL" \
        "all(k in d for k in ('logged_in','email','project_id','expires_at','expires_in_sec','expired','has_refresh','account','pending','profile'))"

# expired session: the CLI says the expiry is in the past
EXPIRED=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
          MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":true,"expires_at":1000000000000,"expired":true,"has_refresh":true,"pending":false}' \
          api "action=status")
json_ok "an expired session reports expired true and a negative remaining time" "$EXPIRED" \
        "d['expired'] is True and d['expires_in_sec'] < 0"

# a far-future expiry must not overflow: expires_in_sec used to be an int, so
# any expiry past 2038 came out as -1987015054 while expired stayed false.
FAR=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
      MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":true,"expires_at":4102444800000,"expired":false,"has_refresh":true}' \
      api "action=status")
json_ok "a post-2038 expiry reports a positive remaining time" "$FAR" \
        "d['expires_in_sec'] > 0 and d['expired'] is False"
json_ok "a post-2038 expiry normalises ms to seconds" "$FAR" \
        "d['expires_at'] == 4102444800"

# pending marker file present -> pending true even without CLI help
: > "$FIX/pending/antigravity-default.json"
PEND=$(ANTIGRAVITY_CREDS_PATH="$FIX/none/antigravity_accounts.json" \
       MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":false,"pending":false}' \
       api "action=status")
json_ok "the pending marker file makes status pending" "$PEND" "d['pending'] is True"
rm -f "$FIX/pending/antigravity-default.json"

# no CLI on PATH: status must still answer from the files alone
NOCLI=$(ANTIGRAVITY_LOGIN_BIN="/nonexistent/login-cli" \
        ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" api "action=status")
json_ok "status answers without the login CLI" "$NOCLI" \
        "d['ok'] is True and d['logged_in'] is True"
json_ok "cli_present is false when the CLI is missing" "$NOCLI" "d['cli_present'] is False"

# format=json with no action means status
FMT=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
      MOCK_STATUS_JSON='{"ok":true,"logged_in":true,"has_refresh":true}' api "format=json")
json_ok "format=json alone answers status" "$FMT" "d['ok'] is True and 'logged_in' in d"

# ---------------------------------------------------------------- start
section "action=start"
START=$(api "action=start")
json_ok "start returns ok + an auth_url" "$START" \
        "d['ok'] is True and d['auth_url'].startswith('https://accounts.google.com/')"
check "start reports the paste_code flow" '"flow":"paste_code"' "$START"
check "start carries the PKCE challenge in the URL" "code_challenge=" "$START"
check "start carries the S256 method" "code_challenge_method=S256" "$START"
check "start reports an expiry window" "expires_in" "$START"

# the plugin must not invent a client secret of its own
check_not "start never echoes a client secret" "GOCSPX" "$START"

NOCLISTART=$(ANTIGRAVITY_LOGIN_BIN="/nonexistent/login-cli" api "action=start")
json_ok "start without the CLI returns a structured error" "$NOCLISTART" \
        "d['ok'] is False and d['error']=='cli_unavailable'"

# ---------------------------------------------------------------- finish
section "action=finish"
MISSING=$(api "action=finish")
json_ok "finish without a code is a 400-style error object" "$MISSING" \
        "d['ok'] is False and d['error']=='missing_code'"

SHELLY=$(api "action=finish&code=\$(touch_/tmp/pwned)")
json_ok "finish rejects shell metacharacters before running anything" "$SHELLY" \
        "d['ok'] is False and d['error']=='invalid_code'"
if [ -e /tmp/pwned ]; then fail "shell injection created /tmp/pwned"; rm -f /tmp/pwned; else pass "shell injection did not execute"; fi

QUOTED=$(api "action=finish&code=abc%27def")
json_ok "finish rejects a quote in the code" "$QUOTED" \
        "d['ok'] is False and d['error']=='invalid_code'"

FAILED=$(MOCK_FAIL=1 api "action=finish&code=4/0AX4XfWh-test-code")
json_ok "a rejected exchange surfaces the CLI error" "$FAILED" \
        "d['ok'] is False and d['error'] in ('exchange','finish_failed')"

# successful exchange: the mock writes the credential files into $MOCK_WRITE_DIR
mkdir -p "$FIX/finishdir"
OKF=$(MOCK_WRITE_DIR="$FIX/finishdir" ANTIGRAVITY_CREDS_PATH="$FIX/finishdir/antigravity_accounts.json" \
      api "action=finish&code=4/0AX4XfWh-test-code")
json_ok "a successful exchange reports done + logged_in" "$OKF" \
        "d['ok'] is True and d['state']=='done' and d['logged_in'] is True"
check "the exchange result re-reads the new account" "pico@example.com" "$OKF"
check_not "the exchange result never carries the token" "1//mock-refresh-token-value" "$OKF"

# a full redirect URL is accepted (the CLI extracts code= itself)
FULLURL=$(MOCK_WRITE_DIR="$FIX/finishdir" ANTIGRAVITY_CREDS_PATH="$FIX/finishdir/antigravity_accounts.json" \
      api "action=finish&code=https%3A%2F%2Fantigravity.google%2Foauth-callback%3Fcode%3D4%2F0AX-test%26state%3Dxyz")
json_ok "a whole redirect URL is accepted" "$FULLURL" "d['ok'] is True and d['state']=='done'"

# POST body carrying the code
POSTB=$(printf '{"code":"4/0AX4XfWh-post-code"}' | \
        REQUEST_METHOD=POST CONTENT_LENGTH=32 \
        MOCK_WRITE_DIR="$FIX/finishdir" ANTIGRAVITY_CREDS_PATH="$FIX/finishdir/antigravity_accounts.json" \
        QUERY_STRING="action=finish" $BIN)
json_ok "the code can arrive in a POST body" "$(body "$POSTB")" "d['ok'] is True"

# ---------------------------------------------------------------- cancel
section "action=cancel"
CANCEL=$(api "action=cancel")
json_ok "cancel reports a cancelled state" "$CANCEL" \
        "d['ok'] is True and d['state']=='cancelled' and d['pending'] is False"

# ---------------------------------------------------------------- refresh
section "action=refresh"
REFR=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" api "action=refresh")
json_ok "refresh succeeds and reports refreshed" "$REFR" \
        "d['ok'] is True and d['refreshed'] is True"
check_not "refresh NEVER returns the access token" "ya29.MOCK-ACCESS-TOKEN-MUST-NOT-LEAK" "$REFR"
check_not "refresh has no access_token key at all" "access_token" "$REFR"
check "refresh reports the project from the token CLI" "proj-mock-42" "$REFR"

REFRFAIL=$(MOCK_TOKEN_FAIL=1 api "action=refresh")
json_ok "a failed refresh returns a structured error" "$REFRFAIL" \
        "d['ok'] is False and d['error']=='refresh_failed'"

REFRNOCLI=$(ANTIGRAVITY_TOKEN_BIN="/nonexistent/token-cli" api "action=refresh")
json_ok "refresh without the token CLI says cli_unavailable" "$REFRNOCLI" \
        "d['ok'] is False and d['error']=='cli_unavailable'"

# ---------------------------------------------------------------- errors
section "unknown routes and actions"
UNK=$(api "action=teleport")
json_ok "an unknown action is a structured error" "$UNK" \
        "d['ok'] is False and d['error']=='unknown_action'"
RAWUNK=$(apiraw "action=teleport")
check "an unknown action returns a 404 Status" "Status: 404 Not Found" "$RAWUNK"
check "the error carries the plugin contract headers" "Content-Type: application/json" "$RAWUNK"
check_not "no response emits Content-Length" "Content-Length" "$RAWUNK"

BADS=$(api "action=status")
check_not "JSON responses carry Cache-Control: no-store" "Cache-Control: no-store" "$BADS"

# ---------------------------------------------------------------- HTML
section "mode 3: HTML UI"
HTMLRAW=$(apiraw "")
HTML=$(body "$HTMLRAW")
check "HTML is served as text/html" "Content-Type: text/html; charset=utf-8" "$HTMLRAW"
check "HTML declares a viewport" "name=\"viewport\"" "$HTML"
check "HTML carries the CSP header" "Content-Security-Policy" "$HTMLRAW"
check "HTML declares color-scheme via the theme tokens" "color-scheme" "$HTML"
check "HTML includes the bot prepaint script" "bot_theme" "$HTML"
check "HTML includes the theme handoff listener" "sx-theme" "$HTML"
check "HTML has the status pill" 'id="pill"' "$HTML"
check "HTML has the start button" 'id="btnStart"' "$HTML"
check "HTML has the paste input" 'id="codeInput"' "$HTML"
check "HTML has the finish button" 'id="btnFinish"' "$HTML"
check "HTML has the cancel button" 'id="btnCancel"' "$HTML"
check "HTML has the refresh button" 'id="btnRefresh"' "$HTML"
check "HTML has the companion project card" "Companion project" "$HTML"
check "HTML uses the two-route API helper" "plugin_antigravity_login" "$HTML"
check "HTML hides the back link in embed mode" "embed-hide" "$HTML"
check_not "HTML loads no CDN script" "<script src=" "$HTML"
check_not "HTML references no external host script" "cdnjs" "$HTML"
check_not "HTML makes no outbound fetch to a third party" "googleapis.com" "$HTML"
check_not "HTML carries no emoji" "🚀" "$HTML"

if command -v python3 >/dev/null 2>&1; then
    printf '%s' "$HTML" > "$FIX/page.html"
    if python3 - "$FIX/page.html" <<'PY'
import re, sys
html = open(sys.argv[1], encoding='utf-8').read()
# every id referenced by getElementById must exist in the markup
ids = set(re.findall(r'id="([^"]+)"', html))
missing = [i for i in re.findall(r"\$\('([^']+)'\)", html) if i not in ids]
sys.exit(1 if missing else 0)
PY
    then pass "every JS element id exists in the markup"
    else fail "the page JS references an element id that is not in the HTML"; fi
fi

# ---------------------------------------------------------------- source hygiene
section "source hygiene"
check_not "source has no OAuth client secret" "GOCSPX" "$(cat src/plugin_antigravity_login.c)"
check_not "source has no Google API key" "AIza" "$(cat src/plugin_antigravity_login.c)"
check_not "source has no GitHub token" "ghp_" "$(cat src/plugin_antigravity_login.c)"
check_not "source has no internal address" "192.168." "$(cat src/plugin_antigravity_login.c src/ui.html)"
check_not "source has no 10.x internal address" "10.0." "$(cat src/plugin_antigravity_login.c src/ui.html)"
check_not "the page has no internal address either" "172.16" "$(cat src/ui.html)"

# no emoji anywhere in the shipped sources (byte-level check, not a regex guess)
if python3 - src/plugin_antigravity_login.c src/ui.html src/bot_theme_plugin.h <<'PY'
import sys, unicodedata
bad = []
for path in sys.argv[1:]:
    for n, line in enumerate(open(path, encoding='utf-8'), 1):
        for ch in line:
            o = ord(ch)
            if o < 0x2000:
                continue
            if 0x2190 <= o <= 0x21FF:      # arrows are typography, not emoji
                continue
            if unicodedata.category(ch) in ('So', 'Sk') or 0x1F000 <= o <= 0x1FAFF:
                bad.append('%s:%d %r' % (path, n, ch))
if bad:
    print('\n'.join(bad[:10]))
    sys.exit(1)
PY
then pass "no emoji in source, page or theme header"
else fail "emoji found in the shipped sources"; fi

# ---------------------------------------------------------------- extra builds
section "cross-target builds"
if command -v musl-gcc >/dev/null 2>&1; then
    if musl-gcc -O2 -std=c99 -static -I src -o "$FIX/musl-bin" src/plugin_antigravity_login.c 2>/dev/null; then
        pass "static musl build"
        MUSLMETA=$("$FIX/musl-bin" --meta)
        check "the musl binary reports the same metadata" '"name":"google"' "$MUSLMETA"
    else fail "static musl build"; fi
else
    echo "  skip  musl-gcc not installed"
fi

if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
    if x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -o "$FIX/win-bin.exe" src/plugin_antigravity_login.c 2>/dev/null; then
        pass "MinGW-w64 build"
        if [ "$(head -c 2 "$FIX/win-bin.exe")" = "MZ" ]; then
            pass "the Windows build has a real PE header"
        else fail "the Windows build is not a PE (missing MZ)"; fi
    else fail "MinGW-w64 build"; fi
else
    echo "  skip  x86_64-w64-mingw32-gcc not installed"
fi

if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
    if aarch64-linux-gnu-gcc -O2 -std=c99 -static -I src -o "$FIX/arm-bin" src/plugin_antigravity_login.c 2>/dev/null; then
        pass "static arm64 build"
    else fail "static arm64 build"; fi
else
    echo "  skip  aarch64-linux-gnu-gcc not installed"
fi

# _FORTIFY_SOURCE=2: the sqlite plugin lost a whole build to this, so it is
# part of every suite now.
if gcc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$FIX/fortify-bin" src/plugin_antigravity_login.c 2>/dev/null; then
    FORTMETA=$("$FIX/fortify-bin" --meta)
    check "a _FORTIFY_SOURCE=2 build runs --meta clean" '"name":"google"' "$FORTMETA"
    FORTSTAT=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
               QUERY_STRING="action=status" "$FIX/fortify-bin")
    json_ok "a fortify build answers status without aborting" "$(body "$FORTSTAT")" "d['ok'] is True"
else
    fail "_FORTIFY_SOURCE=2 build"
fi

# ---------------------------------------------------------------- summary
printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
printf '  %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ] || exit 1
exit 0
