#!/bin/sh
# Saved model endpoints against a fake OpenAI-compatible server: pic endpoints add saves a URL
# and fetches GET {URL}/models; pic models (and RPC's get_available_models) list those models
# as NAME/MODEL, marked as the endpoint's; refresh fetches again, and a failed refresh keeps the
# list and says why; a request for NAME/MODEL goes to the URL's chat completions (with the
# endpoint's key, sealed under its name); the default model and the built-in providers are
# left alone; remove forgets the endpoint and its key; names and URLs are checked; the RPC
# commands do the same. --no-faults (the release build): the key cases, which feed the
# passphrase through PIC_TEST_PASSPHRASE (dev builds only), are skipped.
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}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
C=$(cd "$(dirname "$0")/chat-streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-endpoints.XXXXXX")
T=$(cd "$T" && pwd -P)
spid=
stop() { [ -n "$spid" ] && kill "$spid" 2>/dev/null && wait "$spid" 2>/dev/null || :; spid=; }
cleanup() { stop; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
for v in $(env | sed -nE 's/^([A-Za-z0-9_]*_(API_KEY|TOKEN))=.*/\1/p'); do unset "$v"; done
unset PIC_TEST_PASSPHRASE PIC_MODELS_FILE
mkdir "$T/home" "$T/ws"
export HOME="$T/home" PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0 PIC_NO_KEY_CHECKS=1
pic() { "$PIC" --db "$T/j" --workspace "$T/ws" "$@"; }
# serve NAME SPEC...: a fresh fake server, its requests in $T/NAME/k.req, its port in $port
serve() {
    stop
    name=$1
    shift
    mkdir "$T/$name"
    "$SERVER" "$T/$name.port" "$T/$name" 60 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/$name.port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server $name"; sleep 0.05; done
    port=$(cat "$T/$name.port")
}
printf '{"object":"list","data":[{"id":"gpt-x","object":"model","owned_by":"openai"},{"id":"claude-y","object":"model"}]}' > "$T/list1.json"
printf '{"object":"list","data":[{"id":"gpt-x","owned_by":"openai"},{"id":"claude-y"},{"id":"gemini-z","owned_by":"google"}]}' > "$T/list2.json"
printf '{"error":{"message":"upstream is down","type":"server_error"}}' > "$T/down.json"

# Names and URLs are checked before anything is saved or fetched.
pic endpoints add openai http://127.0.0.1:1/v1 2> "$T/e1" && fail "a built-in provider's name was taken"
grep -q 'openai is a provider pic already has' "$T/e1" || fail "collision: $(cat "$T/e1")"
pic endpoints add 'a/b' http://127.0.0.1:1/v1 2> /dev/null && fail "a name with a slash was saved"
pic endpoints add proxy ftp://127.0.0.1/v1 2> /dev/null && fail "an ftp URL was saved"
pic endpoints add proxy http://example.com/v1 2> "$T/e2" && fail "plain http to another host was saved"
grep -q 'only to this machine' "$T/e2" || fail "http check: $(cat "$T/e2")"
pic endpoints add proxy 'https://u:p@example.com/v1' 2> /dev/null && fail "a URL with a user was saved"
pic endpoints list | grep -q 'No saved endpoints' || fail "a refused add saved something: $(pic endpoints list)"
printf 'PASS: names and URLs are checked; a provider'"'"'s name is never taken\n'

# Add: saved, its models fetched once; the default model and the providers stay as they were.
pic settings defaultModel anthropic/claude-haiku-5-5
pic models --all > "$T/before"
serve add "status:200:$T/list1.json" "status:200:$T/list2.json" "status:500:$T/down.json" "sse:$C/text.sse"
pic endpoints add proxy "http://127.0.0.1:$port/v1/" > "$T/add.out" 2> "$T/add.err" || fail "add: $(cat "$T/add.err")"
grep -q "Saved the endpoint proxy (http://127.0.0.1:$port/v1)" "$T/add.out" || fail "add said: $(cat "$T/add.out")"
grep -q '2 models, in /model as proxy/MODEL' "$T/add.out" || fail "add count: $(cat "$T/add.out")"
head -1 "$T/add/1.req" | grep -q '^GET /v1/models HTTP/1.1' || fail "fetch: $(head -1 "$T/add/1.req")"
grep -qi '^authorization:' "$T/add/1.req" && fail "a key was sent with no key saved"
pic endpoints list > "$T/list"
grep -q "^proxy  *http://127.0.0.1:$port/v1  2 models, fetched " "$T/list" || fail "list: $(cat "$T/list")"
pic models > "$T/models"
grep -q '^proxy/gpt-x  *from proxy$' "$T/models" || fail "pic models: $(grep proxy "$T/models")"
grep -q '^proxy/claude-y ' "$T/models" || fail "pic models: claude-y"
pic models --json | grep -q '^{"model":"proxy/gpt-x","provider":"proxy","id":"gpt-x",.*"available":true,.*"endpoint":"proxy"}$' ||
    fail "json: $(pic models --json | grep proxy/gpt-x)"
pic models --all | grep -v '^proxy/' > "$T/after"
cmp -s "$T/before" "$T/after" || fail "the providers' models changed: $(diff "$T/before" "$T/after" | head -5)"
[ "$(pic settings defaultModel)" = anthropic/claude-haiku-5-5 ] || fail "default after add: $(pic settings defaultModel)"
[ -z "$(pic settings lastModel || true)" ] || fail "lastModel set by add"
printf 'PASS: add saves the URL and lists its models as proxy/MODEL; nothing else changes\n'

# Refresh fetches again; a failed one keeps the list and says why.
pic endpoints refresh proxy > "$T/r1" 2>&1 || fail "refresh: $(cat "$T/r1")"
grep -q '^proxy: 3 models$' "$T/r1" || fail "refresh said: $(cat "$T/r1")"
pic models | grep -q '^proxy/gemini-z ' || fail "refresh: gemini-z not listed"
pic endpoints refresh > "$T/r2" 2>&1 && fail "a failed refresh succeeded"
grep -q "proxy: http://127.0.0.1:$port/v1/models answered HTTP 500: upstream is down (the list it had is kept)" "$T/r2" ||
    fail "failed refresh said: $(cat "$T/r2")"
pic models | grep -q '^proxy/gemini-z ' || fail "failed refresh lost the list"
pic endpoints list > "$T/list"
grep -q '3 models, fetched' "$T/list" || fail "list after failure: $(cat "$T/list")"
grep -q 'the last refresh failed, so this list is older: .*HTTP 500: upstream is down' "$T/list" || fail "list error: $(cat "$T/list")"
printf 'PASS: refresh replaces the list; a failed refresh keeps it and says why\n'

# A request for proxy/gpt-x goes to the URL's chat completions, naming gpt-x; nothing is saved.
pic --model proxy/gpt-x ask 'hi there' > "$T/ask.out" 2> "$T/ask.err" || fail "ask: $(cat "$T/ask.err")"
req=$(grep -l '^POST ' "$T"/add/*.req | head -1)
[ -n "$req" ] || fail "no request reached the endpoint"
head -1 "$req" | grep -q '^POST /v1/chat/completions HTTP/1.1' || fail "request: $(head -1 "$req")"
grep -q '"model":"gpt-x"' "$req" || fail "request model: $(tail -1 "$req" | head -c 300)"
[ "$(pic settings defaultModel)" = anthropic/claude-haiku-5-5 ] || fail "default after ask: $(pic settings defaultModel)"
printf 'PASS: proxy/gpt-x is sent to the endpoint'"'"'s chat completions as gpt-x\n'

# RPC: list, add, refresh, remove; get_available_models marks the endpoint's models.
serve rpc "status:200:$T/list1.json" "status:404:-"
cat > "$T/rpc.in" <<EOF
{"id":"1","type":"get_endpoints"}
{"id":"2","type":"add_endpoint","name":"second","url":"http://127.0.0.1:$port/v1"}
{"id":"3","type":"get_available_models"}
{"id":"4","type":"refresh_endpoints","name":"second"}
{"id":"5","type":"remove_endpoint","name":"second"}
{"id":"6","type":"remove_endpoint","name":"second"}
EOF
pic --mode rpc < "$T/rpc.in" > "$T/rpc.out" 2> "$T/rpc.err" || fail "rpc: $(cat "$T/rpc.err")"
grep '"id":"1"' "$T/rpc.out" | grep -q '"endpoints":\[{"name":"proxy","url":"http://127.0.0.1:[0-9]*/v1","hasKey":false,"models":\[{"id":"gpt-x","owned_by":"openai"},{"id":"claude-y","owned_by":null},' ||
    fail "get_endpoints: $(grep '"id":"1"' "$T/rpc.out")"
grep '"id":"2"' "$T/rpc.out" | grep -q '"success":true.*"data":{"name":"second","count":2}' || fail "add_endpoint: $(grep '"id":"2"' "$T/rpc.out")"
grep '"id":"3"' "$T/rpc.out" | grep -q '"id":"gpt-x",[^}]*"provider":"second".*"endpoint":"second"' ||
    fail "get_available_models: $(grep '"id":"3"' "$T/rpc.out" | head -c 600)"
grep '"id":"4"' "$T/rpc.out" | grep -q '"endpoints":\[{"name":"second","count":0,"error":".*HTTP 404"}\]' ||
    fail "refresh_endpoints: $(grep '"id":"4"' "$T/rpc.out")"
grep '"id":"5"' "$T/rpc.out" | grep -q '"data":{"removed":true}' || fail "remove_endpoint: $(grep '"id":"5"' "$T/rpc.out")"
grep '"id":"6"' "$T/rpc.out" | grep -q '"data":{"removed":false}' || fail "remove_endpoint again: $(grep '"id":"6"' "$T/rpc.out")"
printf 'PASS: the RPC commands list, add, refresh and remove endpoints\n'

# Remove: gone from the list and from pic models; its models no longer resolve.
pic endpoints remove proxy | grep -q 'Removed the endpoint proxy' || fail "remove"
pic endpoints list | grep -q 'No saved endpoints' || fail "list after remove: $(pic endpoints list)"
pic models | grep -q '^proxy/' && fail "models after remove"
pic --model proxy/gpt-x ask hi > /dev/null 2> "$T/gone.err" && fail "a removed endpoint still answered"
grep -q 'unknown' "$T/gone.err" || fail "removed endpoint: $(cat "$T/gone.err")"
pic endpoints remove proxy 2> /dev/null && fail "removing twice succeeded"
printf 'PASS: remove forgets the endpoint and its models\n'

# A 401 from an endpoint with no key says how to add one; --key takes no value.
serve nokey "status:200:$T/list1.json" "status:401:-"
pic endpoints add noauth "http://127.0.0.1:$port/v1" > /dev/null 2> "$T/n.err" || fail "add noauth: $(cat "$T/n.err")"
pic --model noauth/claude-y ask hi > /dev/null 2> "$T/n2.err" && fail "a 401 ask succeeded"
grep -q "this endpoint has no key saved: pic endpoints add noauth http://127.0.0.1:$port/v1 --key asks for one" "$T/n2.err" ||
    fail "401 with no key: $(cat "$T/n2.err")"
pic endpoints add noauth "http://127.0.0.1:$port/v1" --key sk-typed-on-the-line > /dev/null 2> "$T/n3.err" && fail "--key took a value"
grep -q -- '--key takes no value' "$T/n3.err" || fail "--key value: $(cat "$T/n3.err")"
grep -q 'sk-typed-on-the-line' "$T/n3.err" && fail "the value was echoed"
pic endpoints remove noauth > /dev/null
printf 'PASS: a 401 from an endpoint with no key says how to add one; --key takes no value, and says so\n'

if [ "$FAULTS" = yes ]; then
    # A key: sealed under the endpoint's name, sent with the fetch and with requests.
    KEY="pic-endpoint-sentinel-$$"
    serve keyed "status:200:$T/list1.json" "sse:$C/text.sse" "status:401:-"
    printf '%s\n' "$KEY" | PIC_TEST_PASSPHRASE=pass pic endpoints add keyed "http://127.0.0.1:$port/v1" --key > "$T/k.out" 2> "$T/k.err" ||
        fail "add with a key: $(cat "$T/k.err")"
    grep -q 'with its key, sealed' "$T/k.out" || fail "keyed add said: $(cat "$T/k.out")"
    grep -qi "^authorization: Bearer $KEY" "$T/keyed/1.req" || fail "the fetch did not send the key"
    pic keys | grep -q 'keyed' || fail "the key is not stored under the endpoint's name: $(pic keys)"
    PIC_TEST_PASSPHRASE=pass pic --model keyed/claude-y ask hi > /dev/null 2> "$T/k2.err" || fail "keyed ask: $(cat "$T/k2.err")"
    grep -qi "^authorization: Bearer $KEY" "$T/keyed/2.req" || fail "the request did not send the key"
    grep -q '"model":"claude-y"' "$T/keyed/2.req" || fail "keyed request model"
    grep -c "$KEY" "$T/k.out" "$T/k.err" "$T/k2.err" | grep -qv ':0$' && fail "the key was printed"
    PIC_TEST_PASSPHRASE=pass pic --model keyed/claude-y ask hi > /dev/null 2> "$T/k3.err" && fail "a 401 keyed ask succeeded"
    grep -q "the saved key was refused: pic endpoints add keyed http://127.0.0.1:$port/v1 --key asks for a new one" "$T/k3.err" ||
        fail "401 with a key: $(cat "$T/k3.err")"
    pic endpoints remove keyed > /dev/null || fail "remove keyed"
    pic keys | grep -q 'keyed' && fail "the key outlived its endpoint"
    printf 'PASS: an endpoint'"'"'s key is sealed under its name and sent with its fetch and requests\n'
fi
if [ "$FAULTS" = yes ]; then
    # --basic: a user and a password, two lines of stdin, sealed under the endpoint's name and sent
    # as HTTP Basic with the fetch and with requests; never printed, never in models.json.
    PW="pic-basic-sentinel-$$"
    CR=$(printf '\r')
    WANT=$(printf '%s' "alice:$PW" | base64 | tr -d '\n')
    serve basic "status:200:$T/list1.json" "sse:$C/text.sse" "status:401:-" "status:401:-"
    printf 'alice\n%s\n' "$PW" | PIC_TEST_PASSPHRASE=pass pic endpoints add valet "http://127.0.0.1:$port/v1" --basic > "$T/b.out" 2> "$T/b.err" ||
        fail "add --basic: $(cat "$T/b.err")"
    grep -q 'with its user and password, sealed' "$T/b.out" || fail "basic add said: $(cat "$T/b.out")"
    grep -q "^Authorization: Basic $WANT$CR\{0,1\}$" "$T/basic/1.req" || fail "the fetch did not send Basic: $(grep -i '^authorization' "$T/basic/1.req")"
    pic endpoints list > "$T/b.list"
    grep -q 'user alice, password set' "$T/b.list" || fail "list: $(cat "$T/b.list")"
    pic auth status > "$T/b.status" 2>&1 || :
    grep -q 'valet.*user alice, password set' "$T/b.status" || fail "auth status: $(cat "$T/b.status")"
    PIC_TEST_PASSPHRASE=pass pic --model valet/claude-y ask hi > /dev/null 2> "$T/b2.err" || fail "basic ask: $(cat "$T/b2.err")"
    grep -q "^Authorization: Basic $WANT$CR\{0,1\}$" "$T/basic/2.req" || fail "the request did not send Basic"
    head -1 "$T/basic/2.req" | grep -q '^POST /v1/chat/completions' || fail "basic request: $(head -1 "$T/basic/2.req")"
    PIC_TEST_PASSPHRASE=pass pic endpoints refresh valet > "$T/b3.out" 2>&1 && fail "a 401 refresh succeeded"
    grep -q "pic endpoints add valet http://127.0.0.1:$port/v1 --basic" "$T/b3.out" || fail "401 refresh hint: $(cat "$T/b3.out")"
    PIC_TEST_PASSPHRASE=pass pic --model valet/claude-y ask hi > /dev/null 2> "$T/b4.err" && fail "a 401 ask succeeded"
    grep -q "pic endpoints add valet http://127.0.0.1:$port/v1 --basic" "$T/b4.err" || fail "401 ask hint: $(cat "$T/b4.err")"
    grep -c "$PW" "$T/b.out" "$T/b.err" "$T/b.list" "$T/b.status" "$T/b2.err" "$T/b3.out" "$T/b4.err" "$HOME/.pic/models.json" 2> /dev/null |
        grep -qv ':0$' && fail "the password was printed or written to models.json"
    printf 'alice\n\n' | PIC_TEST_PASSPHRASE=pass pic endpoints add valet2 "http://127.0.0.1:$port/v1" --basic 2> /dev/null && fail "an empty password was sealed"
    printf 'al:ice\npw\n' | PIC_TEST_PASSPHRASE=pass pic endpoints add valet2 "http://127.0.0.1:$port/v1" --basic 2> /dev/null && fail "a user with a colon was sealed"
    pic endpoints remove valet > /dev/null || fail "remove valet"
    pic keys | grep -q 'valet' && fail "the password outlived its endpoint"
    printf 'PASS: --basic seals a user and password and sends HTTP Basic; a 401 says how to fix it\n'
fi
# The terminal interface: /model lists the endpoint's models marked "from NAME", with rows to
# add another endpoint (a small form) and to refresh the saved ones.
serve tui "status:200:$T/list1.json" "status:200:$T/list2.json"
pic endpoints add proxy "http://127.0.0.1:$port/v1" > /dev/null || fail "add for the picker"
screen() { perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$1" | grep -v '^\s*$' | tail -16; }
cat > "$T/tui.in" <<EOF
expect new conversation
send /model\r
expect Select a model
send gpt-x
expect from proxy
send \x1b
wait 300
send /model\r
expect Select a model
send endpoint
expect Add an endpoint
expect Refresh endpoint models
send \r
expect Name (its models are NAME/MODEL):
send third
send \r
expect URL:
send http://127.0.0.1:$port/v1
send \r
expect API key (Enter for none, Tab for a user and password):
send \r
expect Saved the endpoint third: 3 models, in /model as third/MODEL
send /model\r
expect Select a model
send endpoint
expect Refresh endpoint models
send \x1b[B
wait 300
send \r
expect Endpoints refreshed: proxy: 3 models; third: 3 models
send \x1b
wait 300
send \x04\x04
EOF
"$DRIVE" "$T/tui.tx" 140 30 "$PIC" --tui-mode regular --db "$T/j" --workspace "$T/ws" < "$T/tui.in" || fail "picker: $(screen "$T/tui.tx")"
pic endpoints list | grep -q "^third  *http://127.0.0.1:$port/v1  3 models" || fail "the form did not save: $(pic endpoints list)"
[ "$(pic settings defaultModel)" = anthropic/claude-haiku-5-5 ] || fail "default after the picker: $(pic settings defaultModel)"
printf 'PASS: /model shows an endpoint'"'"'s models as from it; its rows add an endpoint and refresh them\n'
if [ "$FAULTS" = yes ]; then
    # The form's Tab at the key step asks for a user and a password instead, sent as HTTP Basic.
    TPW="pic-form-sentinel-$$"
    cat > "$T/tui2.in" <<EOF
expect new conversation
send /model\r
expect Select a model
send endpoint
expect Add an endpoint
send \r
expect Name (its models are NAME/MODEL):
send fourth
send \r
expect URL:
send http://127.0.0.1:$port/v1
send \r
expect API key (Enter for none, Tab for a user and password):
send \t
expect User:
send bob
send \r
expect Password:
send $TPW
send \r
expect Passphrase for pic's credential store
send pass
send \r
expect Stop asking for this passphrase
send n
expect Saved the endpoint fourth: 3 models, in /model as fourth/MODEL
send \x04\x04
EOF
    PIC_TEST_PASSPHRASE=pass "$DRIVE" "$T/tui2.tx" 140 30 "$PIC" --tui-mode regular --db "$T/j" --workspace "$T/ws" < "$T/tui2.in" ||
        fail "basic form: $(screen "$T/tui2.tx")"
    WANT2=$(printf '%s' "bob:$TPW" | base64 | tr -d '\n')
    grep -l "^Authorization: Basic $WANT2" "$T"/tui/*.req > /dev/null 2>&1 || fail "the form's fetch did not send Basic"
    pic endpoints list | grep -q 'user bob, password set' || fail "list after the form: $(pic endpoints list)"
    printf 'PASS: the picker form takes a user and password for HTTP Basic\n'
fi
