#!/bin/sh
# tests/run.sh - offline checks for plugin_opencode_login across all 3 modes.
#
# Every check runs against ./plugin_opencode_login with the credential paths
# and both CLIs redirected at throwaway fixtures, so the suite proves the public
# contract without touching a real OpenCode session and without a network.
#
# What it proves:
#   - --meta is exactly {"name":"opencode","desc":"OpenCode 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 reads the credential json, the pending marker and the CLI answer
#     and never emits a token
#   - start returns the CLI's verify_url + user_code; poll walks pending ->
#     done and re-reads state; a dead flow reports failed, not an infinite
#     spinner; cancel clears the marker
#   - refresh re-reads the token through the token CLI and drops the value
#   - 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_opencode_login
ID=plugin_opencode_login
PASS=0
FAIL=0

# A token planted in the fixtures that must never surface in any response.
SECRET="oc-mock-access-token-must-not-leak"
REFRESH_SECRET="oc-mock-refresh-token-must-not-leak"
DEVICE_SECRET="oc-mock-device-code-must-not-leak"

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)"; printf '       got: %s\n' "$(printf '%s' "$3" | head -c 300)"
        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_opencode_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 ocfix)
trap 'rm -rf "$FIX"' EXIT

NOW=$(date +%s)
FUT=$((NOW + 86400))
PAST=$((NOW - 3600))

mkdir -p "$FIX/none" "$FIX/empty" "$FIX/full" "$FIX/expired" "$FIX/alt/.opencode" "$FIX/alt/.config/opencode" "$FIX/pending" "$FIX/env"
export OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh"
export OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh"
export OPENCODE_PENDING_PATH="$FIX/pending/opencode-default.json"
export OPENCODE_ENV_DIR="$FIX/env"

# empty credentials file (exists but holds no token)
: > "$FIX/empty/auth.json"

# a live session: token, refresh token, org, future expiry
printf '{"access_token":"%s","refresh_token":"%s","token_type":"Bearer","expires_in":2591999,"expires_at":%s,"org_id":"org-mock-42"}\n' \
    "$SECRET" "$REFRESH_SECRET" "$FUT" > "$FIX/full/auth.json"

# an expired session
printf '{"access_token":"%s","refresh_token":"%s","token_type":"Bearer","expires_at":%s,"org_id":"org-mock-42"}\n' \
    "$SECRET" "$REFRESH_SECRET" "$PAST" > "$FIX/expired/auth.json"

# the secondary ~/.opencode/token.json layout the spec names
printf '{"access_token":"%s","expires_at":%s}\n' "$SECRET" "$FUT" > "$FIX/alt/.opencode/token.json"

# The pending device flow marker is written per section, exactly as the CLI
# writes it, so a test that expects "nothing pending" never sees a leftover.

# ---------------------------------------------------------------- metadata
section "--meta / discovery"
META=$($BIN --meta)
check "--meta via argv"        '"name":"opencode"'    "$META"
check "--meta desc"            '"desc":"OpenCode login"' "$META"
check_not "--meta leaks nothing else" "expires" "$META"
METAENV=$(SX_PLUGIN_META=1 $BIN)
check "--meta via SX_PLUGIN_META" '"name":"opencode"' "$METAENV"
json_ok "--meta is a valid JSON object" "$META" "isinstance(d,dict) and d['name']=='opencode' and d['desc']=='OpenCode login'"
# 1-word title, 14-char desc (the market contract floor)
check_not "--meta title is one word" '"name":"opencode login"' "$META"
DESCLEN=$(printf '%s' "OpenCode login" | wc -c)
if [ "$DESCLEN" -le 15 ]; then pass "desc fits the 15-char limit ($DESCLEN)"; else fail "desc too long ($DESCLEN)"; fi

VERSION=$($BIN --version)
check "--version reports the id" "plugin_opencode_login 1.0.0" "$VERSION"

# ---------------------------------------------------------------- auth gate
section "node auth gate"
export BOT_PASSWORD=test-node-password
NOAUTH=$(QUERY_STRING="action=status" $BIN)
check "unauthenticated status is 401" "Status: 401 Unauthorized" "$NOAUTH"
check "401 body says invalid node password" "invalid node password" "$NOAUTH"
check_not "401 does not leak the password" "test-node-password" "$NOAUTH"
for a in start poll cancel refresh; do
    check "action=$a is gated" "Status: 401" "$(QUERY_STRING="action=$a" $BIN)"
done
check "meta stays open without a password" '"name":"opencode"' "$($BIN --meta)"
check "password via ?pwd= is accepted" '"ok":true' "$(QUERY_STRING="action=status&pwd=test-node-password" $BIN)"
check "password via X-Bot-Password is accepted" '"ok":true' \
    "$(HTTP_X_BOT_PASSWORD=test-node-password QUERY_STRING="action=status" $BIN)"
check "password via Bearer is accepted" '"ok":true' \
    "$(HTTP_AUTHORIZATION='Bearer test-node-password' QUERY_STRING="action=status" $BIN)"
check "wrong password still 401s" "Status: 401" "$(QUERY_STRING="action=status&pwd=wrong" $BIN)"
BODYAUTH=$(printf '{"a":1}' | CONTENT_LENGTH=9 QUERY_STRING="action=status" $BIN)
check "a POST body does not bypass the gate" "Status: 401" "$BODYAUTH"
unset BOT_PASSWORD

# ---------------------------------------------------------------- status: no session
section "status - no session"
rm -f "$FIX/pending/opencode-default.json"
export OPENCODE_CREDS_PATH="$FIX/none/auth.json"
S=$(api "action=status")
json_ok "status with no credential file is valid JSON" "$S" "d['ok'] is True and d['logged_in'] is False"
check "no session reports logged_in false" '"logged_in":false' "$S"
check "no session reports pending false"    '"pending":false'    "$S"
check "no session reports has_refresh false" '"has_refresh":false' "$S"
check "no session reports expires_at 0"     '"expires_at":0'     "$S"
check "no session reports expired false"    '"expired":false'    "$S"
check "no session names the CLI protocol"   '"protocol":"SXLOGIN-MACHINE-V1"' "$S"
check "no session reports the CLI present"  '"cli_present":true' "$S"
check "no session reports the token CLI"    '"token_cli_present":true' "$S"
check_not "empty status leaks no token"     "$SECRET" "$S"

# ---------------------------------------------------------------- status: empty file
section "status - empty credential file"
export OPENCODE_CREDS_PATH="$FIX/empty/auth.json"
S=$(api "action=status")
json_ok "empty credential file is not a session" "$S" "d['logged_in'] is False"
check "empty file still reports a path" "$FIX/empty/auth.json" "$S"

# ---------------------------------------------------------------- status: live session
section "status - live session"
rm -f "$FIX/pending/opencode-default.json"
export OPENCODE_CREDS_PATH="$FIX/full/auth.json"
S=$(api "action=status")
json_ok "live session is valid JSON" "$S" "d['ok'] is True and d['logged_in'] is True"
check "live session reports logged_in true"  '"logged_in":true'  "$S"
check "live session reports has_refresh"     '"has_refresh":true' "$S"
check "live session reports expired false"   '"expired":false'   "$S"
check "live session carries the org account" '"account":"org-mock-42"' "$S"
check "live session carries org_id"          '"org_id":"org-mock-42"' "$S"
check "live session carries a username"      '"username":"org-mock-42"' "$S"
json_ok "live session expiry is in the future" "$S" "d['expires_in_sec'] > 80000 and d['expires_at'] > 0"
check "live session names the profile"       '"profile":"superopencode"' "$S"
check_not "status never prints the access token"  "$SECRET" "$S"
check_not "status never prints the refresh token" "$REFRESH_SECRET" "$S"
check_not "status never uses the word access_token" "access_token" "$S"
check_not "status never uses the word refresh_token" "refresh_token" "$S"

# ---------------------------------------------------------------- status: expired
section "status - expired session"
rm -f "$FIX/pending/opencode-default.json"
export OPENCODE_CREDS_PATH="$FIX/expired/auth.json"
S=$(api "action=status")
json_ok "expired session is still reported" "$S" "d['logged_in'] is True and d['expired'] is True"
check "expired session flags expired true" '"expired":true' "$S"
json_ok "expired session reports a negative window" "$S" "d['expires_in_sec'] < 0"
check_not "expired status leaks no token" "$SECRET" "$S"

# ---------------------------------------------------------------- status: pending marker
section "status - pending device flow"
printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \
    > "$FIX/pending/opencode-default.json"
export OPENCODE_CREDS_PATH="$FIX/none/auth.json"
S=$(api "action=status")
check "a marker file means pending true"  '"pending":true'  "$S"
check "pending reports its age"           '"pending_age_sec":' "$S"
check_not "pending status does not leak the device code" "$DEVICE_SECRET" "$S"
# a stale marker (older than the CLI's 900 s TTL) must not keep the spinner on
printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$((NOW - 1200))" \
    > "$FIX/pending/opencode-default.json"
S=$(api "action=status")
json_ok "a stale marker is not pending" "$S" "d['pending'] is False"
rm -f "$FIX/pending/opencode-default.json"

# ---------------------------------------------------------------- status: format=json
section "format=json is status"
rm -f "$FIX/pending/opencode-default.json"
export OPENCODE_CREDS_PATH="$FIX/full/auth.json"
S=$(api "format=json")
json_ok "format=json alone returns a status object" "$S" "d['ok'] is True and 'logged_in' in d"
S=$(api "action=status&format=json")
json_ok "action and format together still work" "$S" "d['logged_in'] is True"
S=$(apiraw "action=unknown")
check "an unknown action is a 400" "Status: 400 Bad Request" "$S"
check "unknown action names the valid ones" "expected status, start, poll, cancel or refresh" "$S"

# ---------------------------------------------------------------- status: alt path
section "secondary credential location"
rm -f "$FIX/pending/opencode-default.json"
# No OPENCODE_CREDS_PATH override: the plugin must fall back to
# $HOME/.opencode/token.json when ~/.config/opencode/auth.json is absent.
unset OPENCODE_CREDS_PATH
export HOME="$FIX/alt"
mkdir -p "$FIX/alt/.config/opencode"
S=$(api "action=status")
json_ok "the ~/.opencode/token.json fallback is read" "$S" "d['logged_in'] is True"
check "the fallback path is reported" "$FIX/alt/.opencode/token.json" "$S"
check_not "the fallback status leaks no token" "$SECRET" "$S"
# the primary file wins when both exist
printf '{"access_token":"%s","expires_at":%s,"org_id":"org-primary"}\n' "$SECRET" "$FUT" \
    > "$FIX/alt/.config/opencode/auth.json"
S=$(api "action=status")
check "the primary credential file wins" "org-primary" "$S"
export HOME=/root
export OPENCODE_CREDS_PATH="$FIX/full/auth.json"

# ---------------------------------------------------------------- start
section "start - device flow"
rm -f "$FIX/pending/opencode-default.json"
S=$(api "action=start")
json_ok "start returns a device_code flow" "$S" "d['ok'] is True and d['flow']=='device_code'"
check "start hands back the verify url" "https://opencode.ai/console/device" "$S"
check "start hands back the user code"  '"user_code":"ABCD-EFGH"' "$S"
check "start reports pending true"      '"pending":true'  "$S"
json_ok "start reports an expiry window" "$S" "d['expires_in'] >= 60"
check_not "start does not leak the device code" "$DEVICE_SECRET" "$S"
check_not "start leaks no token" "$SECRET" "$S"

# start when credentials already exist
export MOCK_START_FAIL=1
S=$(api "action=start")
unset MOCK_START_FAIL
json_ok "an existing session is reported, not a crash" "$S" "d.get('already_logged_in') is True"
check "existing session tells the user to re-login" "already_logged_in" "$S"
check "existing session hints at force" "force=1" "$S"
S=$(api "action=start&force=1")
check "force=1 starts over an existing session" '"user_code":"ABCD-EFGH"' "$S"
export MOCK_START_NETFAIL=1
S=$(api "action=start")
unset MOCK_START_NETFAIL
check "a network failure surfaces as an error" '"error":"network"' "$S"

# ---------------------------------------------------------------- poll
section "poll - pending then done"
rm -f "$FIX/pending/opencode-default.json"
printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \
    > "$FIX/pending/opencode-default.json"
export OPENCODE_CREDS_PATH="$FIX/none/auth.json"
S=$(api "action=poll")
json_ok "poll while waiting is pending" "$S" "d['ok'] is True and d['state']=='pending'"
check "pending poll says logged_in false" '"logged_in":false' "$S"
check "pending poll carries an interval"  '"interval":5'      "$S"
check_not "pending poll leaks no secret"  "$DEVICE_SECRET" "$S"

# approval: the mock CLI writes the credential file and clears the marker
export MOCK_APPROVE=1
rm -f "$FIX/full2" ; mkdir -p "$FIX/full2"
export OPENCODE_CREDS_PATH="$FIX/full2/auth.json"
S=$(api "action=poll")
json_ok "poll after approval is done" "$S" "d['ok'] is True and d['state']=='done' and d['logged_in'] is True"
check "done poll reports a live session" '"logged_in":true' "$S"
check "done poll carries the fresh expiry" '"expires_in_sec":' "$S"
check_not "done poll does not print the token" "$SECRET" "$S"
check_not "done poll does not print the refresh token" "$REFRESH_SECRET" "$S"
unset MOCK_APPROVE
rm -f "$FIX/full2/auth.json"

# a denied flow is terminal
printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \
    > "$FIX/pending/opencode-default.json"
export OPENCODE_CREDS_PATH="$FIX/none/auth.json"
export MOCK_DENY=1
S=$(api "action=poll")
unset MOCK_DENY
json_ok "a denial is reported as a failed state" "$S" "d['ok'] is True and d['state']=='failed'"
check "a denial names the error" '"error":"denied"' "$S"
check "a denial clears pending" '"pending":false' "$S"

# no pending marker at all
rm -f "$FIX/pending/opencode-default.json"
export MOCK_NO_PENDING=1
S=$(api "action=poll")
unset MOCK_NO_PENDING
json_ok "polling with nothing pending fails cleanly" "$S" "d['state']=='failed'"
check "nothing-pending explains itself" "run --start first" "$S"

# ---------------------------------------------------------------- cancel
section "cancel"
printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \
    > "$FIX/pending/opencode-default.json"
S=$(api "action=cancel")
json_ok "cancel succeeds" "$S" "d['ok'] is True and d['state']=='cancelled'"
check "cancel clears pending" '"pending":false' "$S"
if [ -f "$FIX/pending/opencode-default.json" ]; then
    fail "cancel removed the marker file"
else
    pass "cancel removed the marker file"
fi
check_not "cancel leaks no device code" "$DEVICE_SECRET" "$S"

# ---------------------------------------------------------------- refresh
section "refresh"
rm -f "$FIX/pending/opencode-default.json"
export OPENCODE_CREDS_PATH="$FIX/full/auth.json"
S=$(api "action=refresh")
json_ok "refresh succeeds on a live session" "$S" "d['ok'] is True and d['refreshed'] is True"
check "refresh reports the session again" '"logged_in":true' "$S"
check "refresh keeps the org account"     '"account":"org-mock-42"' "$S"
check_not "refresh never prints the token" "$SECRET" "$S"
check_not "refresh never prints the refresh token" "$REFRESH_SECRET" "$S"

# refresh with no session
export OPENCODE_CREDS_PATH="$FIX/none/auth.json"
S=$(api "action=refresh")
json_ok "refresh without a session is a clean error" "$S" "d['ok'] is False and d['error']=='not_logged_in'"

# refresh when the token CLI fails
export OPENCODE_CREDS_PATH="$FIX/full/auth.json"
export MOCK_TOKEN_FAIL=1
S=$(api "action=refresh")
unset MOCK_TOKEN_FAIL
json_ok "a failing token CLI is a clean error" "$S" "d['ok'] is False and d['error']=='refresh_failed'"
check_not "a failing refresh leaks no token" "$SECRET" "$S"

# ---------------------------------------------------------------- missing CLIs
section "missing CLIs"
rm -f "$FIX/pending/opencode-default.json"
export OPENCODE_LOGIN_BIN="$FIX/definitely-not-a-binary"
export OPENCODE_TOKEN_BIN="$FIX/definitely-not-a-binary"
export OPENCODE_CREDS_PATH="$FIX/full/auth.json"
S=$(api "action=status")
json_ok "status survives a missing login CLI" "$S" "d['ok'] is True"
check "a missing CLI is reported honestly" '"cli_present":false' "$S"
check "a missing CLI names itself" '"cli_error":"cli_not_found"' "$S"
check "the file-derived session is still reported" '"logged_in":true' "$S"
S=$(apiraw "action=start")
check "start on a missing CLI is cli_unavailable" '"error":"cli_unavailable"' "$S"
check_not "start on a missing CLI is not a 500" "Status: 5" "$S"
S=$(api "action=poll")
check "poll on a missing CLI is cli_unavailable" '"error":"cli_unavailable"' "$S"
S=$(api "action=refresh")
check "refresh on a missing CLI is refresh_unavailable" '"error":"refresh_unavailable"' "$S"
S=$(api "action=cancel")
check "cancel on a missing CLI still clears pending" '"pending":false' "$S"
export OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh"
export OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh"

# ---------------------------------------------------------------- HTML
section "HTML UI"
HTML=$(body "$(QUERY_STRING="" $BIN)")
check "page is a real document"     "<!DOCTYPE html>" "$HTML"
check "page titles the tool"        "<title>opencode</title>" "$HTML"
check "page has the status pill"    'id="pill"' "$HTML"
check "page has the user badge"     'id="userBadge"' "$HTML"
check "page has the start button"   'id="btnStartLogin"' "$HTML"
check "page has the copy button"    'id="btnCopyOpen"' "$HTML"
check "page has the user code box"  'id="userCode"' "$HTML"
check "page has the poll indicator" 'id="pollLabel"' "$HTML"
check "page has the cancel button"  'id="btnCancel"' "$HTML"
check "page has the refresh button" 'id="btnRefresh"' "$HTML"
check "page has the re-login button" 'id="btnRelogin"' "$HTML"
check "page names the device flow"  "Device Flow" "$HTML"
check "page carries the copy label" "Copy Code" "$HTML"
check "page uses the bot theme handoff" "sx-theme" "$HTML"
check "page reads the theme before paint" "data-theme" "$HTML"
check "page hides its toggle when embedded" "embed-hide" "$HTML"
check "page uses the two-route API helper" "plugin_opencode_login" "$HTML"
check "page fluid down to 390px" "max-width:480px" "$HTML"
check_not "page loads no CDN script"  "<script src=" "$HTML"
check_not "page references no cdnjs"  "cdnjs" "$HTML"
check_not "page makes no third-party fetch" "googleapis.com" "$HTML"
check_not "page carries no rocket emoji" "\xf0\x9f\x9a\x80" "$HTML"
check_not "page never mentions a token variable" "access_token" "$HTML"
check_not "page hardcodes no LAN address" "192.168." "$HTML"
check_not "page hardcodes no localhost port" "127.0.0.1" "$HTML"

# the served page must be parseable and every JS id must exist in the markup
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()
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

    if python3 - "$FIX/page.html" <<'PY'
import sys
html = open(sys.argv[1], encoding='utf-8').read()
# balanced tags for the containers the page actually builds
for tag in ("div", "span", "button", "script", "style"):
    opens = html.count("<%s" % tag)
    closes = html.count("</%s>" % tag)
    if opens != closes:
        sys.stderr.write("%s: %d open vs %d close\n" % (tag, opens, closes))
        sys.exit(1)
sys.exit(0)
PY
    then pass "the page markup is balanced"
    else fail "the page markup has unbalanced tags"; fi
fi

# ---------------------------------------------------------------- source hygiene
section "source hygiene"
check_not "source has no GitHub token"     "ghp_"      "$(cat src/plugin_opencode_login.c)"
check_not "source has no scorpiox-git PAT" "3ef2c00"   "$(cat src/plugin_opencode_login.c)"
# the needle is split so this file never contains the string it looks for
check_not "source has no default password" "xbo""xone" "$(cat src/plugin_opencode_login.c src/ui.html tests/mock_login.sh tests/mock_token.sh)"
check_not "source has no internal address" "192.168."  "$(cat src/plugin_opencode_login.c src/ui.html)"
check_not "source has no 10.x address"     "10.0."     "$(cat src/plugin_opencode_login.c src/ui.html)"
check_not "source has no host name"        "macmini"   "$(cat src/plugin_opencode_login.c src/ui.html)"
check_not "source has no device secret"    "$DEVICE_SECRET" "$(cat src/plugin_opencode_login.c src/ui.html)"
check_not "no Content-Length header is emitted" "Content-Length" "$(cat src/plugin_opencode_login.c)"

# no emoji anywhere in the shipped sources (byte-level check, not a regex guess)
if python3 - src/plugin_opencode_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

# plugin.json sidecar must carry the market contract
if command -v python3 >/dev/null 2>&1; then
    if python3 - plugin.json <<'PY'
import json, sys
d = json.load(open(sys.argv[1]))
want = {
    "slug": "opencode-login",
    "id": "plugin_opencode_login",
    "name": "opencode",
    "desc": "OpenCode login",
    "title": "OpenCode Login",
    "category": "devtools",
    "license": "MIT",
}
for k, v in want.items():
    if d.get(k) != v:
        sys.stderr.write("%s: %r != %r\n" % (k, d.get(k), v))
        sys.exit(1)
if d.get("capabilities") != ["credentials_read", "oauth_device_flow"]:
    sys.stderr.write("capabilities wrong\n"); sys.exit(1)
if "never" not in d.get("trust_notice", "").lower():
    sys.stderr.write("trust_notice must promise what never leaves the node\n"); sys.exit(1)
sys.exit(0)
PY
    then pass "plugin.json carries the full market contract"
    else fail "plugin.json does not match the contract"; fi
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_opencode_login.c 2>/dev/null; then
        pass "static musl build"
        MUSLMETA=$("$FIX/musl-bin" --meta)
        check "the musl binary reports the same metadata" '"name":"opencode"' "$MUSLMETA"
        MUSLS=$(HOME=/root QUERY_STRING="action=status" "$FIX/musl-bin" >/dev/null 2>&1 && echo ran)
        check "the musl binary runs a status call" "ran" "$MUSLS"
    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_opencode_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_opencode_login.c 2>/dev/null; then
        pass "static aarch64 build"
        # an aarch64 ELF cannot be exec'd on an x86_64 host, so the artifact is
        # verified by its header instead of by running it.
        if python3 - "$FIX/arm-bin" <<'PY'
import sys
b = open(sys.argv[1], "rb").read(20)
# ELF magic, class 2 (64-bit), little endian; e_machine sits at offset 18
# (e_type is at 16) and 183 = AArch64.
ok = b[:4] == b"\x7fELF" and b[4] == 2 and b[5] == 1
ok = ok and int.from_bytes(b[18:20], "little") == 183
sys.exit(0 if ok else 1)
PY
        then pass "the arm artifact is a little-endian aarch64 ELF"
        else fail "the arm artifact is not an aarch64 ELF"; fi
    else fail "static aarch64 build"; fi
else
    echo "  skip  aarch64-linux-gnu-gcc not installed"
fi

# _FORTIFY_SOURCE=2: a hardened build must still run, because dist packaging on
# some distros compiles with it defined by default.
if gcc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$FIX/fortify-bin" src/plugin_opencode_login.c 2>/dev/null; then
    FORTMETA=$("$FIX/fortify-bin" --meta)
    check "a _FORTIFY_SOURCE=2 build runs --meta clean" '"name":"opencode"' "$FORTMETA"
    FORTSTAT=$(OPENCODE_CREDS_PATH="$FIX/full/auth.json" OPENCODE_PENDING_PATH="$FIX/pending/none.json" \
               OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh" \
               OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh" \
               OPENCODE_ENV_DIR="$FIX/env" \
               QUERY_STRING="action=status" "$FIX/fortify-bin" | tr -d '\r' | tail -1)
    check "a _FORTIFY_SOURCE=2 build serves status" '"logged_in":true' "$FORTSTAT"
    FORTSTART=$(OPENCODE_PENDING_PATH="$FIX/pending/none.json" \
                OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh" \
                OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh" \
                OPENCODE_ENV_DIR="$FIX/env" \
                QUERY_STRING="action=start" "$FIX/fortify-bin" | tr -d '\r' | tail -1)
    check "a _FORTIFY_SOURCE=2 build serves start" '"flow":"device_code"' "$FORTSTART"
    FORTBAD=$(OPENCODE_PENDING_PATH="$FIX/pending/none.json" \
              OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh" \
              OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh" \
              OPENCODE_ENV_DIR="$FIX/env" \
              QUERY_STRING="action=zzz" "$FIX/fortify-bin" | tr -d '\r' | head -1)
    check "a _FORTIFY_SOURCE=2 build rejects a bad action" "Status: 400" "$FORTBAD"
else
    fail "_FORTIFY_SOURCE=2 build"
fi

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