#!/bin/sh
# Choosing a model in the terminal interface, on a pseudo-terminal against a
# fake server: the first screen says why this model (or that there is no key
# yet); a refused key offers Alt+P, and the message goes to the model picked
# instead of being dropped; the picker shows prices and key marks, ranks
# exact and prefix matches first, shows models with no key once something is
# typed, says when the pick is saved and when the thinking level changes.
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}
S=$(cd "$(dirname "$0")/../pic/streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-tui-models.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; }
for v in $(env | sed -nE 's/^([A-Za-z0-9_]*_(API_KEY|TOKEN))=.*/\1/p'); do unset "$v"; done
unset PIC_TEST_PASSPHRASE
mkdir "$T/ws" "$T/log" "$T/home"
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
printf '{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}' > "$T/auth.json"
# 1 fake refuses its key, then replies; free key checks get a 404, which says nothing about a key
"$SERVER" "$T/port" "$T/log" 120 "at:/v1/models=status:404:-" "status:401:$T/auth.json" "sse:$S/text.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server"; sleep 0.05; done
port=$(cat "$T/port")
cat > "$T/models.json" <<EOF
{"providers":{
 "good":{"baseUrl":"http://127.0.0.1:$port","api":"anthropic-messages","apiKey":"\$GOOD_API_KEY","models":[
  {"id":"m","contextWindow":200000,"reasoning":true,"cost":{"input":0.1,"output":0.4}},
  {"id":"glm-flash-latest","contextWindow":200000},
  {"id":"flash-latest","contextWindow":200000,"reasoning":true,"thinkingLevelMap":{"minimal":null,"low":null,"medium":null}}]},
 "fake":{"baseUrl":"http://127.0.0.1:$port","api":"anthropic-messages","apiKey":"\$FAKE_API_KEY","models":[
  {"id":"m","contextWindow":200000,"cost":{"input":3,"output":15}}]}}}
EOF
screen() { perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$1" | grep -v '^\s*$' | tail -12; }
drive() { # NAME ARGS...: pic on a pseudo-terminal, the script on stdin
    name=$1
    shift
    "$DRIVE" "$T/$name.tx" 120 30 "$PIC" --tui-mode regular --db "$T/j" --workspace "$T/ws" "$@" || fail "$name: $(screen "$T/$name.tx")"
}

# No key anywhere: the first screen says how to get one.
drive nokey <<'EOF'
expect No key yet: /login, or export a provider key such as OPENROUTER_API_KEY
send \x04\x04
EOF
printf 'PASS: with no key, the first screen says how to get one\n'

# One key: the first screen names the model and why.
GOOD_API_KEY=pic-tui-good drive why <<'EOF'
expect pic good/m
expect model good/m (GOOD_API_KEY is set; Alt+P to change)
send \x04\x04
EOF
printf 'PASS: the first screen names the model and why it was chosen\n'

# A refused key: Alt+P picks another model, and Enter sends the same message to it.
GOOD_API_KEY=pic-tui-good FAKE_API_KEY=pic-tui-fake drive refused --model fake/m <<'EOF'
expect pic fake/m
send hello there\r
expect fake refused the key "env"
expect or Alt+P to pick another model
send \ep
expect Select a model
expect $3/$15 · key refused
send good/m
expect $0.1/$0.4
send \r
expect Your message is back in the editor: Enter sends it to good/m.
send \r
expect Hello, "world"
send \x04\x04
EOF
grep -q 'hello there' "$T/log/2.req" || fail "refused: the message did not go to the new model"
printf 'PASS: after a refused key, Alt+P picks another model and Enter sends the message to it\n'

# The picker: exact and prefix matches first, models with no key once typed,
# the saved default said plainly, a thinking level the model lacks said.
GOOD_API_KEY=pic-tui-good drive picker --model good/m <<'EOF'
expect pic good/m
send \ep
expect Select a model
expect Prices: $ per million tokens in/out
send flash-latest
expect →   flash-latest [good]
send \r
expect model good/flash-latest; new conversations start on it
expect thinking level high: this model does not offer medium
send \ep
expect Select a model
send gpt-6.2-sol
expect no key
send \e
send \x04\x04
EOF
[ "$("$PIC" --db "$T/j" --workspace "$T/ws" settings defaultModel)" = good/flash-latest ] || fail "picker: default not saved"
printf 'PASS: the picker ranks exact and prefix matches first, marks keys and prices, and says what it saved\n'
