#!/bin/sh
# The terminal interface's free key checks, on a pseudo-terminal against a
# fake server: starting up checks the active key once, in the background (a
# provider that never answers holds nothing up); opening /key checks the keys
# not checked in the last ten minutes and shows their credit as the answers
# arrive; a key checked a moment ago is not checked again (not by a second
# /key either); only free GETs go out and no key reaches the screen. Keys are
# variables, since the store stays locked until a request asks for the
# passphrase and a background check never does.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
DRIVE=${DRIVE:?set DRIVE to the pty_drive binary}
SQLITE3=${SQLITE3:-sqlite3}
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-keyprobe.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/ws" "$T/log" "$T/home"
for v in $(env | sed -nE 's/^([A-Za-z0-9_]*_(API_KEY|TOKEN))=.*/\1/p'); do unset "$v"; done
unset PIC_NO_KEY_CHECKS PIC_TEST_PASSPHRASE
KF="pic-keyprobe-fake-$$"
KO="pic-keyprobe-openrouter-$$"
export HOME="$T/home" PIC_MODELS_FILE="$T/models.json" PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0 T
export PIC_NO_NATIVE_CLIPBOARD=1
export FAKE_API_KEY="$KF" OPENROUTER_API_KEY="$KO"
printf '{"data":{"limit":10,"limit_remaining":4.12}}' > "$T/or.json"
printf '{"data":[{"id":"m1"}]}' > "$T/models.body"
serve() { # SPEC...
    [ -n "$spid" ] && kill "$spid" 2>/dev/null || :
    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"; sleep 0.05; done
    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}}]},"openrouter":{"baseUrl":"http://127.0.0.1:%s/api/v1"}}}' \
        "$(cat "$T/port")" "$(cat "$T/port")" > "$T/models.json"
}
requests() { ls "$T/log" | wc -l | tr -d ' '; }
drive() { # NAME: pic on a pseudo-terminal, the script on stdin
    name=$1
    shift
    "$DRIVE" "$T/$name.tx" 100 30 "$PIC" --tui-mode regular --db "$T/j" --workspace "$T/ws" --model fake/m "$@" ||
        fail "$name: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$name.tx" | grep -v '^\s*$' | tail -12)"
}
state_of() { "$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT state || '|' || coalesce(remaining, '') FROM picu_credential_health WHERE name LIKE '$1%'"; }

# Starting up checks the active key (fake's variable) and nothing else; /key checks the rest, once.
serve "at:/v1/models=status:200:$T/models.body" "at:/api/v1/key=status:200:$T/or.json"
drive first <<EOF
expect pic fake/m
waitfile \$T/log/1.req
wait 800
send /key\r
expect Keys
expect \$4.12 left
send \e
wait 300
send /key\r
expect Keys
expect \$4.12 left
send \e
wait 200
send \x04\x04
EOF
[ "$(requests)" = 2 ] || fail "first: $(requests) requests, wanted the startup check and openrouter's (no repeats)"
for f in "$T/log"/*.req; do head -1 "$f" | grep -q '^GET ' || fail "first: a check sent $(head -1 "$f")"; done
grep -q "^x-api-key: $KF" "$(grep -l '^GET /v1/models ' "$T/log"/*.req)" || fail "first: the startup check did not send the active key"
grep -q "^Authorization: Bearer $KO" "$(grep -l '^GET /api/v1/key ' "$T/log"/*.req)" || fail "first: /key did not check openrouter's key"
case $(state_of env:FAKE_API_KEY) in "ok|") ;; *) fail "first: fake's state $(state_of env:FAKE_API_KEY)" ;; esac
case $(state_of env:OPENROUTER_API_KEY) in "ok|4.12") ;; *) fail "first: openrouter's state $(state_of env:OPENROUTER_API_KEY)" ;; esac
! grep -aqF -- "$KF" "$T/first.tx" && ! grep -aqF -- "$KO" "$T/first.tx" || fail "first: a key reached the screen"
printf 'PASS: startup checks the active key; /key checks the others as answers arrive; nothing twice\n'

# A provider that never answers: the interface is up at once and quits at once.
"$SQLITE3" "$HOME/.pic/pic.sqlite" "DELETE FROM picu_credential_health"
serve "at:/v1/models=hang:$T/models.body:30" "at:/api/v1/key=hang:$T/or.json:30"
t0=$(date +%s)
drive hang <<EOF
expect pic fake/m
send /key\r
expect Keys
send \e
wait 200
send \x04\x04
EOF
t1=$(date +%s)
[ $((t1 - t0)) -lt 12 ] || fail "hang: the interface waited $((t1 - t0)) s on a check"
printf 'PASS: a check that gets no answer holds nothing up\n'
