#!/bin/sh
# tests/run.sh - offline checks for plugin_google_quota across all 3 modes.
#
# Runs against ./plugin_google_quota with credential paths and the quota CLI
# redirected at throwaway fixtures, proving the contract without network access.

set -u

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

BIN=./plugin_google_quota
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() {
    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() {
    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"; }

body() {
    printf '%s\n' "$1" | tr -d '\r' | awk '
        BEGIN { inhdr = 0 }
        NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options):/) { inhdr = 1; next }
        inhdr && $0 == "" { inhdr = 0; next }
        inhdr { next }
        { print }
    '
}

json_ok() {
    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
    gcc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src -o "$BIN" src/plugin_google_quota.c || {
        fail "native build"; exit 1; }
fi
pass "native binary present"

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

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 gqfix)
trap 'rm -rf "$FIX"' EXIT

mkdir -p "$FIX/none" "$FIX/empty" "$FIX/full"
chmod +x "$ROOT/tests/mock_quota.sh"
export GOOGLE_QUOTA_BIN="$ROOT/tests/mock_quota.sh"
export GOOGLE_ACCESS_TOKEN="ya29.INHERITED-TOKEN-MUST-BE-CLEARED"
export MOCK_RESET_CLAUDE=$(python3 -c "from datetime import datetime,timedelta,timezone; print((datetime.now(timezone.utc)+timedelta(hours=2,minutes=15)).strftime('%Y-%m-%dT%H:%M:%SZ'))")
export MOCK_RESET_GEMINI=$(python3 -c "from datetime import datetime,timedelta,timezone; print((datetime.now(timezone.utc)+timedelta(hours=144,minutes=30)).strftime('%Y-%m-%dT%H:%M:%SZ'))")

cat > "$FIX/full/antigravity_accounts.json" <<'EOF'
[
  {"email": "alpha@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-A"},
  {"email": "beta@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-B"},
  {"email": "broken@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-C"}
]
EOF
printf 'beta@example.com\n' > "$FIX/full/selected_account.txt"

# ---------------------------------------------------------------- meta & auth
section "meta & auth"
META=$(BOT_PASSWORD=secret-pass $BIN --meta)
check "--meta returns short name and desc without auth" '{"name":"google quota","desc":"Account quotas"}' "$META"

META_ENV=$(BOT_PASSWORD=secret-pass SX_PLUGIN_META=1 $BIN)
check "SX_PLUGIN_META=1 works without auth" '{"name":"google quota","desc":"Account quotas"}' "$META_ENV"

VER=$($BIN --version)
check "--version prints plugin id and version" "plugin_google_quota 1.0.3" "$VER"
UNAUTH=$(BOT_PASSWORD=secret-pass QUERY_STRING="action=status" $BIN)
check "missing password returns 401" "Status: 401 Unauthorized" "$UNAUTH"

AUTH_HDR=$(BOT_PASSWORD=secret-pass HTTP_X_BOT_PASSWORD=secret-pass GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status")
json_ok "X-Bot-Password header authorizes request" "$AUTH_HDR" "d['ok'] is True"

AUTH_BEARER=$(BOT_PASSWORD=secret-pass HTTP_AUTHORIZATION="Bearer secret-pass" GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status")
json_ok "Bearer header authorizes request" "$AUTH_BEARER" "d['ok'] is True"

AUTH_QS=$(BOT_PASSWORD=secret-pass GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status&pwd=secret-pass")
json_ok "?pwd= query param authorizes request" "$AUTH_QS" "d['ok'] is True"

# ---------------------------------------------------------------- status
section "status"
ST_NONE=$(GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status")
json_ok "missing accounts file returns count 0" "$ST_NONE" "d['ok'] is True and d['count'] == 0 and d['cli_present'] is True"

ST_EMPTY=$(GOOGLE_ACCOUNTS_FILE="$FIX/empty/antigravity_accounts.json" api "action=status")
json_ok "empty accounts file returns count 0" "$ST_EMPTY" "d['ok'] is True and d['count'] == 0"

ST_FULL=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=status")
json_ok "full accounts status lists 3 accounts and selected" "$ST_FULL" \
    "d['ok'] is True and d['count'] == 3 and d['selected'] == 'beta@example.com' and d['accounts'][1]['selected'] is True and all(a['has_refresh'] for a in d['accounts'])"
check_not "status never leaks refresh_token" "MOCK-REFRESH-TOKEN" "$ST_FULL"

ST_NOCLI=$(GOOGLE_QUOTA_BIN="/nonexistent/scorpiox-google-quota" GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=status")
json_ok "missing CLI sets cli_present false" "$ST_NOCLI" "d['ok'] is True and d['cli_present'] is False"

# ---------------------------------------------------------------- quota
section "quota"
Q_ONE=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota&account=alpha@example.com")
json_ok "single account quota parses gemini, argon, and claude pools and remaining hours" "$Q_ONE" \
    "d['ok'] is True and d['account']['ok'] is True and abs(d['account']['gemini']['pct'] - 85.5) < 0.01 and abs(d['account']['argon']['pct'] - 100.0) < 0.01 and abs(d['account']['claude']['pct'] - 100.0) < 0.01 and len(d['account']['models']) == 9 and d['account']['gemini']['reset_in_seconds'] > 500000 and d['account']['gemini']['reset_in_hours'] > 140 and 'd ' in d['account']['gemini']['reset_remaining'] and d['account']['claude']['reset_in_seconds'] > 7000 and 'h ' in d['account']['claude']['reset_remaining'] and all('reset_remaining' in m and 'reset_in_hours' in m for m in d['account']['models'])"
json_ok "single account quota parses both 5-hour and weekly limits" "$Q_ONE" \
    "abs(d['account']['limits']['gemini']['five_hour']['pct'] - 37.5) < 0.01 and abs(d['account']['limits']['gemini']['weekly']['pct'] - 85.5) < 0.01 and 'd ' in d['account']['limits']['gemini']['weekly']['reset_remaining'] and 'h ' in d['account']['limits']['gemini']['five_hour']['reset_remaining'] and abs(d['account']['limits']['claude']['five_hour']['pct'] - 100.0) < 0.01 and abs(d['account']['limits']['claude']['weekly']['pct'] - 99.0) < 0.01"
check_not "single quota never leaks token" "MOCK-TOKEN" "$Q_ONE"
check_not "single quota never leaks refresh token" "MOCK-REFRESH-TOKEN" "$Q_ONE"

Q_EXH=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota&account=beta@example.com")
json_ok "null/missing remainingFraction marks gemini pool exhausted with reset remaining" "$Q_EXH" \
    "d['ok'] is True and d['account']['gemini']['exhausted'] is True and d['account']['gemini']['pct'] == 0.0 and abs(d['account']['claude']['pct'] - 42.0) < 0.01 and d['account']['gemini']['reset_in_hours'] > 140 and 'd ' in d['account']['gemini']['reset_remaining']"
json_ok "free account missing gemini 5h returns null five_hour and exhausted weekly" "$Q_EXH" \
    "d['account']['limits']['gemini']['five_hour'] is None and d['account']['limits']['gemini']['weekly']['exhausted'] is True and d['account']['limits']['gemini']['weekly']['pct'] == 0.0 and abs(d['account']['limits']['claude']['five_hour']['pct'] - 50.0) < 0.01 and abs(d['account']['limits']['claude']['weekly']['pct'] - 42.0) < 0.01"
Q_ALL=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota")
json_ok "all-accounts quota aggregates best_gemini, best_argon, best_claude, and broken account" "$Q_ALL" \
    "d['ok'] is True and d['count'] == 3 and d['best_gemini'] == 'alpha@example.com' and d['best_argon'] == 'alpha@example.com' and d['best_claude'] == 'alpha@example.com' and d['accounts'][2]['ok'] is False"

Q_FMT=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "format=json")
json_ok "?format=json returns full quota JSON" "$Q_FMT" "d['ok'] is True and d['count'] == 3 and 'best_gemini' in d"

Q_UNK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=quota&account=nobody@example.com")
check "unknown account returns 404" "Status: 404 Not Found" "$Q_UNK"

Q_NOCLI=$(GOOGLE_QUOTA_BIN="/nonexistent/scorpiox-google-quota" GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota")
json_ok "missing CLI returns cli_unavailable" "$Q_NOCLI" "d['ok'] is False and d['error'] == 'cli_unavailable'"

# ---------------------------------------------------------------- switch
section "switch"
SW_OK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=switch&account=alpha@example.com")
json_ok "switch updates selected account" "$SW_OK" "d['ok'] is True and d['selected'] == 'alpha@example.com'"
check "selected_account.txt persisted" "alpha@example.com" "$(cat "$FIX/full/selected_account.txt")"

printf '{"account":"beta@example.com"}' > "$FIX/post.json"
SW_PBF=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" POST_BODY_FILE="$FIX/post.json" api "action=switch")
json_ok "switch accepts POST_BODY_FILE JSON" "$SW_PBF" "d['ok'] is True and d['selected'] == 'beta@example.com'"

SW_BAD=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=switch&account=bad;rm")
check "invalid email rejected with 400" "Status: 400 Bad Request" "$SW_BAD"

SW_UNK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=switch&account=nobody@example.com")
check "unknown email rejected with 404" "Status: 404 Not Found" "$SW_UNK"

# ---------------------------------------------------------------- HTML UI
section "HTML UI"
HTML=$(apiraw "")
check "HTML emits Content-Type text/html" "Content-Type: text/html" "$HTML"
check "HTML includes bot theme prepaint" "bot_theme" "$HTML"
check "HTML includes theme handoff" "sx-theme-request" "$HTML"
check "HTML uses two-route API helper" "plugin_google_quota" "$HTML"
check "HTML hub proxy URL uses &action= separator" "'/plugins?plugin='+encodeURIComponent(HUB)+'&'" "$HTML"
check "HTML formats multi-day remaining resets cleanly" "d+'d '+h+'h'" "$HTML"
check "HTML renders both 5-hour and weekly limit sections" "5-Hour Limit" "$HTML"
check "HTML renders weekly limit label" "Weekly Limit" "$HTML"
check "HTML renders per-model reset remaining hours" "fmtResetShort" "$HTML"
check "HTML includes live reset countdown attributes" "data-reset" "$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 googleapis" "googleapis.com" "$HTML"
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]
if missing:
    print("missing ids:", missing)
    sys.exit(1)
PY
then pass "every JS element id exists in the markup"
else fail "JS references missing element id"; fi

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

if python3 - src/plugin_google_quota.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:
                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 shipped sources"; fi

# ---------------------------------------------------------------- cross-target 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_google_quota.c 2>/dev/null; then
        pass "static musl build"
        check "musl binary reports --meta" '"name":"google quota"' "$("$FIX/musl-bin" --meta)"
    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_google_quota.c 2>/dev/null; then
        pass "MinGW-w64 build"
        if [ "$(head -c 2 "$FIX/win-bin.exe")" = "MZ" ]; then
            pass "Windows build has PE header"
        else fail "Windows build missing MZ header"; 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_google_quota.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

if gcc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$FIX/fortify-bin" src/plugin_google_quota.c 2>/dev/null; then
    pass "_FORTIFY_SOURCE=2 build"
else
    fail "_FORTIFY_SOURCE=2 build"
fi

printf '\n%sSummary:%s %d passed, %d failed\n' "$C_B" "$C_0" "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]
