#!/bin/sh
# Free checks of a key, against a fake server, with a private HOME: pic auth
# status --check asks each provider's free endpoint (OpenRouter's key,
# DeepSeek's balance, the models list of the rest), all at once, and shows
# what comes back ("$4.12 left", a yen balance, "valid, checked ..."); each
# answer is read as a request's reply would be (refused, out of credit,
# limited until a time); a models list never clears a failure a reply taught;
# no key is probed twice in ten minutes unless --check forces it; --active
# and a provider name narrow the set; a check that gets no answer neither
# blocks nor changes a state; print, JSON and RPC modes never check; a key's
# text is sent only to its provider's own base URL and shown nowhere; an old
# health table gains its columns. --no-faults (the release build): skipped
# whole, since the passphrase comes from PIC_TEST_PASSPHRASE, which only the
# dev build reads.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
SQLITE3=${SQLITE3:-sqlite3}
if [ "${1:-}" = --no-faults ]; then
    printf 'SKIP: probes needs the dev build (PIC_TEST_PASSPHRASE)\n'
    exit 0
fi
S=$(cd "$(dirname "$0")/streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-probes.XXXXXX")
T=$(cd "$T" && pwd -P)
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null || :; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
mkdir "$T/home" "$T/ws" "$T/out"
for v in $(env | sed -nE 's/^([A-Za-z0-9_]*_(API_KEY|TOKEN))=.*/\1/p'); do unset "$v"; done
unset FAKE_API_KEY
PASS="pic-probes-passphrase-$$"
KA="pic-probes-anthropic-$$-a1"
KW="pic-probes-work-$$-a2"
KO="pic-probes-openrouter-$$-b1"
KI="pic-probes-openai-$$-c1"
KD="pic-probes-deepseek-$$-d1"
export PIC_NO_KEY_CHECKS= # the suites run with it on; a login here checks the key it saves
export HOME="$T/home" PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0 PIC_MODELS_FILE="$T/models.json" PIC_TEST_PASSPHRASE="$PASS"
export DEEPSEEK_API_KEY="$KD"
DB="$HOME/.pic/pic.sqlite"

round=0
serve() { # SPEC...: a fresh server, its log in $T/log
    [ -n "$spid" ] && kill "$spid" 2>/dev/null || :
    [ -n "$spid" ] && wait "$spid" 2>/dev/null || :
    round=$((round + 1))
    rm -rf "$T/log" "$T/port"
    mkdir "$T/log"
    "$SERVER" "$T/port" "$T/log" 120 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server did not start"; sleep 0.05; done
    P=$(cat "$T/port")
    printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$FAKE_API_KEY","models":[{"id":"m","contextWindow":200000,"cost":{"input":3,"output":15}}]},"anthropic":{"baseUrl":"http://127.0.0.1:%s"},"openrouter":{"baseUrl":"http://127.0.0.1:%s/api/v1"},"deepseek":{"baseUrl":"http://127.0.0.1:%s"},"openai":{"baseUrl":"http://127.0.0.1:%s/openai/v1"}}}' \
        "$P" "$P" "$P" "$P" "$P" > "$T/models.json"
}
pic() { # NAME ARGS...: stdout and stderr in $T/out/NAME.{out,err}
    name=$1
    shift
    "$PIC" --db "$T/j" --workspace "$T/ws" --model fake/m "$@" > "$T/out/$name.out" 2> "$T/out/$name.err" < /dev/null
}
requests() { ls "$T/log" | wc -l | tr -d ' '; }
request_for() { grep -l "^GET $1 " "$T/log"/*.req 2> /dev/null | head -1; }
row() { # NAME PROVIDER LABEL REGEX: the table line must match
    grep -q "^$2  *$3\*\{0,1\}  *[A-Za-z_ ]*  *$4" "$T/out/$1.out" || fail "$1: no '$2 $3 $4' in: $(cat "$T/out/$1.out")"
}
state_of() { "$SQLITE3" "$DB" "SELECT state || '|' || coalesce(reason, '') || '|' || coalesce(remaining, '') || '|' || coalesce(unit, '') FROM picu_credential_health WHERE name = '$1'"; }

printf '{"data":{"label":"k","limit":10,"limit_remaining":4.12,"usage":5.88}}' > "$T/or.json"
printf '{"data":{"limit":10,"limit_remaining":0}}' > "$T/or0.json"
printf '{"data":{"limit":null,"limit_remaining":null}}' > "$T/ornull.json"
printf '{"data":{"limit":10,"limit_remaining":3}}' > "$T/or3.json"
printf '{"is_available":true,"balance_infos":[{"currency":"CNY","total_balance":"110.00","granted_balance":"10.00","topped_up_balance":"100.00"}]}' > "$T/ds.json"
printf '{"is_available":false,"balance_infos":[{"currency":"CNY","total_balance":"0.00"}]}' > "$T/ds0.json"
printf '{"is_available":true,"balance_infos":[{"currency":"CNY","total_balance":"80.00"},{"currency":"USD","total_balance":"12.5"}]}' > "$T/dsboth.json"
printf '{"data":[{"id":"m1"}]}' > "$T/models.json.body"
printf '{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}' > "$T/auth.json"
printf '{"error":"not found"}' > "$T/notfound.json"
printf '{"error":{"message":"Insufficient credits"}}' > "$T/credits.json"
printf '{"type":"error","error":{"type":"rate_limit_error","message":"slow down"}}' > "$T/rate.json"

serve "sse:$S/text.sse"
# Keys: anthropic's own and a named one, openrouter's and openai's stored; deepseek's is the variable.
printf '%s\n' "$KA" | "$PIC" --db "$T/j" --workspace "$T/ws" login anthropic > /dev/null 2> "$T/out/l1.err" || fail "login anthropic: $(cat "$T/out/l1.err")"
printf '%s\n' "$KW" | "$PIC" --db "$T/j" --workspace "$T/ws" auth login anthropic --api-key --as work > /dev/null 2> "$T/out/l2.err" || fail "login work: $(cat "$T/out/l2.err")"
printf '%s\n' "$KO" | "$PIC" --db "$T/j" --workspace "$T/ws" login openrouter > /dev/null 2> "$T/out/l3.err" || fail "login openrouter: $(cat "$T/out/l3.err")"
printf '%s\n' "$KI" | "$PIC" --db "$T/j" --workspace "$T/ws" login openai > /dev/null 2> "$T/out/l4.err" || fail "login openai: $(cat "$T/out/l4.err")"

# ---- each kind of check, all at once ----
serve "at:/v1/models=head:200:$T/models.json.body:anthropic-ratelimit-requests-remaining: 99|anthropic-ratelimit-requests-limit: 100" \
    "at:/openai/v1/models=status:200:$T/models.json.body" "at:/api/v1/key=status:200:$T/or.json" "at:/user/balance=status:200:$T/ds.json"
pic all auth status --check || fail "check: $(cat "$T/out/all.err")"
row all openrouter default 'API key  *\$4.12 left'
row all deepseek env 'DEEPSEEK_API_KEY  *¥110.00 left'
row all anthropic default 'API key  *valid, checked just now'
row all anthropic work 'API key  *valid, checked just now'
row all openai default 'API key  *valid, checked just now'
[ "$(requests)" = 5 ] || fail "check: $(requests) requests, wanted one per key (5)"
for f in "$T/log"/*.req; do head -1 "$f" | grep -q '^GET ' || fail "a check sent more than a GET: $(head -1 "$f")"; done
f=$(request_for /api/v1/key) || fail "no GET /api/v1/key"
grep -q "^Authorization: Bearer $KO" "$f" || fail "openrouter: its key did not go to its key endpoint"
f=$(request_for /user/balance) || fail "no GET /user/balance"
grep -q "^Authorization: Bearer $KD" "$f" || fail "deepseek: its key did not go to its balance endpoint"
f=$(request_for /openai/v1/models) || fail "no GET /openai/v1/models"
grep -q "^Authorization: Bearer $KI" "$f" || fail "openai: its key did not go to its models list"
grep -q "^x-api-key: $KA" "$T/log"/*.req || fail "anthropic: the default key was not sent"
grep -q "^x-api-key: $KW" "$T/log"/*.req || fail "anthropic: the work key was not sent"
grep -qi '^anthropic-version: ' "$T/log"/*.req || fail "anthropic: no version header"
if grep -l "$KA\|$KW" "$T/log"/*.req | xargs grep -l "openrouter\|deepseek\|user/balance" > /dev/null 2>&1; then fail "a key went to another provider's endpoint"; fi
for k in "$KO" "$KD" "$KI"; do
    n=$(grep -l "$k" "$T/log"/*.req | wc -l | tr -d ' ')
    [ "$n" = 1 ] || fail "a key was sent $n times in one check"
done
case $(state_of anthropic) in "ok|requests left: 99|"*) ;; *) fail "anthropic's rate-limit header was not recorded: $(state_of anthropic)" ;; esac
case $(state_of openrouter) in "ok||4.12|"*) ;; *) fail "openrouter: $(state_of openrouter)" ;; esac
printf 'PASS: --check asks each provider its free endpoint: credit for OpenRouter and DeepSeek, validity for the rest\n'

# ---- cached for ten minutes; --check forces ----
pic cached auth status --refresh || fail "refresh: $(cat "$T/out/cached.err")"
pic plain auth status || fail "status: $(cat "$T/out/plain.err")"
[ "$(requests)" = 5 ] || fail "cache: --refresh or a plain status probed again ($(requests) requests)"
row cached openrouter default 'API key  *\$4.12 left'
pic forced auth status --check || fail "check again: $(cat "$T/out/forced.err")"
[ "$(requests)" = 10 ] || fail "force: $(requests) requests after a second --check, wanted 10"
# an hour later the cache has lapsed: --refresh checks again, but never asks for the passphrase, so
# only the key that is not in the locked store (deepseek's variable) is checked
"$SQLITE3" "$DB" "UPDATE picu_credential_health SET probed_ms = probed_ms - 3600000, checked_ms = checked_ms - 3600000"
pic stale auth status --refresh || fail "refresh: $(cat "$T/out/stale.err")"
[ "$(requests)" = 11 ] || fail "stale: $(requests) requests after the cache lapsed, wanted 11 (the variable alone)"
printf 'PASS: a key is not checked twice in ten minutes unless --check forces it\n'

# ---- narrowing ----
pic active auth status --check --active || fail "active: $(cat "$T/out/active.err")"
[ "$(requests)" = 15 ] || fail "--active: $(requests) requests, wanted 4 more (the work key is not the one in use)"
pic one auth status --check anthropic || fail "provider: $(cat "$T/out/one.err")"
[ "$(requests)" = 17 ] || fail "PROVIDER: $(requests) requests, wanted 2 more"
grep -q '^openrouter' "$T/out/one.out" && fail "PROVIDER: the table lists another provider"
pic badarg auth status --active && fail "--active alone was taken"
grep -q -- '--active needs --check or --refresh' "$T/out/badarg.err" || fail "badarg: $(cat "$T/out/badarg.err")"
printf 'PASS: --active and a provider name narrow the keys checked\n'

# ---- refusals read as a request's are ----
serve "at:/v1/models=status:401:$T/auth.json" "at:/api/v1/key=status:402:$T/credits.json" \
    "at:/openai/v1/models=head:429:$T/rate.json:retry-after: 900" "at:/user/balance=status:200:$T/ds0.json"
pic bad auth status --check || fail "bad: $(cat "$T/out/bad.err")"
row bad anthropic default 'API key  *refused since [0-9:]* (HTTP 401)'
row bad anthropic work 'API key  *refused since [0-9:]* (HTTP 401)'
row bad openrouter default 'API key  *out of credit since [0-9:]* (HTTP 402)'
row bad openai default 'API key  *limited until'
row bad deepseek env 'DEEPSEEK_API_KEY  *out of credit since [0-9:]*$'
printf 'PASS: a 401, a 402, a long 429 and an empty balance are read as a request would read them\n'

# ---- a models list does not undo what a reply taught; a balance does ----
serve "at:/v1/models=status:200:$T/models.json.body" "at:/openai/v1/models=status:200:$T/models.json.body" \
    "at:/api/v1/key=status:200:$T/or3.json" "at:/user/balance=status:200:$T/dsboth.json"
pic good auth status --check || fail "good: $(cat "$T/out/good.err")"
row good anthropic default 'API key  *valid, checked just now'
row good openai default 'API key  *valid · last request failed [0-9: -]* (limited until [0-9: -]*)'
row good openrouter default 'API key  *\$3.00 left'
row good deepseek env 'DEEPSEEK_API_KEY  *\$12.50 left'
printf 'PASS: a refused key is valid again at once; a limit stays until it lifts; a balance replaces a spent one\n'

# ---- a spent key limit and a key with no limit ----
serve "at:/api/v1/key=status:200:$T/or0.json"
pic zero auth status --check openrouter || fail "zero: $(cat "$T/out/zero.err")"
row zero openrouter default 'API key  *out of credit since'
"$SQLITE3" "$DB" "DELETE FROM picu_credential_health WHERE name = 'openrouter'"
serve "at:/api/v1/key=status:200:$T/ornull.json"
pic nolimit auth status --check openrouter || fail "nolimit: $(cat "$T/out/nolimit.err")"
row nolimit openrouter default 'API key  *valid, checked just now'
printf 'PASS: a key at its spending limit is out of credit; one with no limit is valid\n'

# ---- no answer: no block, no state ----
"$SQLITE3" "$DB" "DELETE FROM picu_credential_health"
serve "at:/user/balance=hang:$T/ds.json:10" "at:/api/v1/key=status:200:$T/or.json" "at:/v1/models=status:404:$T/notfound.json" \
    "at:/openai/v1/models=status:200:$T/models.json.body"
t0=$(date +%s)
PIC_PROBE_DEADLINE=1 pic hang auth status --check || fail "hang: $(cat "$T/out/hang.err")"
t1=$(date +%s)
[ $((t1 - t0)) -lt 8 ] || fail "hang: a check that got no answer took $((t1 - t0)) s"
row hang deepseek env 'DEEPSEEK_API_KEY  *check failed: no answer in time'
row hang openrouter default 'API key  *\$4.12 left'
row hang anthropic default 'API key  *check failed (HTTP 404)'
row hang openai default 'API key  *valid, checked just now'
printf 'PASS: a check with no answer or a 404 learns nothing and holds nothing up\n'

# ---- a key is checked as it is saved ----
KB="pic-probes-bogus-$$-e1"
KG="pic-probes-good-$$-e2"
serve "at:/v1/models=status:401:$T/auth.json"
printf '%s\n' "$KB" | "$PIC" --db "$T/j" --workspace "$T/ws" login anthropic > "$T/out/sv1.out" 2> "$T/out/sv1.err" || fail "save refused: $(cat "$T/out/sv1.err")"
grep -q 'anthropic refused the key "default" (HTTP 401' "$T/out/sv1.err" || fail "save: a refused key was not said: $(cat "$T/out/sv1.err")"
grep -q 'pic auth logout anthropic forgets it' "$T/out/sv1.err" || fail "save: no way to forget it: $(cat "$T/out/sv1.err")"
grep -q '^Saved the API key' "$T/out/sv1.out" || fail "save: the key was not kept: $(cat "$T/out/sv1.out")"
[ "$(requests)" = 1 ] || fail "save: $(requests) requests, wanted the one check"
grep -q "^x-api-key: $KB" "$T/log"/*.req || fail "save: the new key was not the one checked"
printf '%s\n' "$KB" | "$PIC" --db "$T/j" --workspace "$T/ws" auth login anthropic --api-key --as spare > "$T/out/sv2.out" 2> "$T/out/sv2.err" || fail "save named: $(cat "$T/out/sv2.err")"
grep -q 'pic auth logout anthropic:spare forgets it' "$T/out/sv2.err" || fail "save named: $(cat "$T/out/sv2.err")"
[ "$(requests)" = 2 ] || fail "save named: $(requests) requests, wanted one more, for the new key alone"
serve "at:/v1/models=head:200:$T/models.json.body:anthropic-ratelimit-requests-remaining: 99"
printf '%s\n' "$KG" | "$PIC" --db "$T/j" --workspace "$T/ws" login anthropic > "$T/out/sv3.out" 2> "$T/out/sv3.err" || fail "save good: $(cat "$T/out/sv3.err")"
[ ! -s "$T/out/sv3.err" ] || fail "save: a valid key was complained of: $(cat "$T/out/sv3.err")"
case $(state_of anthropic) in "ok|"*) ;; *) fail "save: a replaced key kept the old verdict: $(state_of anthropic)" ;; esac
PIC_NO_KEY_CHECKS=1 sh -c 'printf "%s\n" "$1" | "$2" --db "$3" --workspace "$4" login openai > /dev/null 2>&1' sh "$KI" "$PIC" "$T/j" "$T/ws" || fail "save with checks off"
[ "$(requests)" = 1 ] || fail "save: PIC_NO_KEY_CHECKS did not stop the check ($(requests) requests)"
printf '%s\n' "/Users/me/.keys/anthropic" | "$PIC" --db "$T/j" --workspace "$T/ws" login anthropic > /dev/null 2> "$T/out/sv4.err" && fail "save: a file path was taken for a key"
grep -q 'looks like a file path' "$T/out/sv4.err" || fail "save: $(cat "$T/out/sv4.err")"
printf '%s\n' "https://example.com/key" | "$PIC" --db "$T/j" --workspace "$T/ws" login anthropic > /dev/null 2> "$T/out/sv5.err" && fail "save: a web address was taken for a key"
grep -q 'looks like a web address' "$T/out/sv5.err" || fail "save: $(cat "$T/out/sv5.err")"
printf 'PASS: a key is checked as it is saved (a refusal says how to forget it), a replaced key sheds its old verdict, a path or an address is not taken for a key\n'

# ---- never in print, JSON or RPC mode ----
serve "sse:$S/text.sse"
"$SQLITE3" "$DB" "DELETE FROM picu_credential_health"
FAKE_API_KEY=pic-probes-fake-$$ pic printed -p hello || fail "print: $(cat "$T/out/printed.err")"
FAKE_API_KEY=pic-probes-fake-$$ pic json --mode json -p hello || fail "json: $(cat "$T/out/json.err")"
printf '%s\n' '{"id":"1","type":"get_state"}' | FAKE_API_KEY=pic-probes-fake-$$ "$PIC" --db "$T/j" --workspace "$T/ws" --model fake/m --mode rpc \
    > "$T/out/rpc.out" 2> "$T/out/rpc.err" || fail "rpc: $(cat "$T/out/rpc.err")"
for f in "$T/log"/*.req; do head -1 "$f" | grep -q '^POST ' || fail "a non-interactive run sent $(head -1 "$f")"; done
[ "$(requests)" = 2 ] || fail "print and JSON: $(requests) requests, wanted their two"
printf 'PASS: print, JSON and RPC modes never check a key\n'

# ---- no key text in any output ----

for k in "$KA" "$KW" "$KO" "$KI" "$KD" "$KB" "$KG" "pic-probes-fake-$$"; do
    grep -rl "$k" "$T/out" && fail "a key appeared in output"
done
printf 'PASS: no key text in any output\n'

# ---- an old health table gains its columns ----
mkdir "$T/old"
mkdir "$T/old/.pic"
"$SQLITE3" "$T/old/.pic/pic.sqlite" "CREATE TABLE picu_credential_health(name TEXT PRIMARY KEY, state TEXT NOT NULL CHECK(state IN ('ok', 'invalid', 'credit', 'limited', 'transient', 'other')), reason TEXT, status INTEGER, until_ms INTEGER, checked_ms INTEGER NOT NULL, remaining REAL); INSERT INTO picu_credential_health VALUES('anthropic', 'credit', NULL, 402, NULL, 1000, 4.5);"
HOME="$T/old" "$PIC" --db "$T/j" --workspace "$T/ws" auth status > /dev/null 2> "$T/out/old.err" || fail "old table: $(cat "$T/out/old.err")"
cols=$("$SQLITE3" "$T/old/.pic/pic.sqlite" "SELECT group_concat(name) FROM pragma_table_info('picu_credential_health') WHERE name IN ('unit', 'probed_ms')")
case $cols in *unit* ) case $cols in *probed_ms*) ;; *) fail "old table: columns $cols" ;; esac ;; *) fail "old table: columns $cols" ;; esac
[ "$("$SQLITE3" "$T/old/.pic/pic.sqlite" "SELECT state FROM picu_credential_health")" = credit ] || fail "old table: the row changed"
printf 'PASS: a health table from before free checks gains unit and probed_ms and keeps its rows\n'
