#!/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.
# The picker is a panel (docs/manual/models.md): it opens during a reply
# without touching it, takes every key while open, and a model chosen then
# is the next request's; /model NAME switches at once on one clear match.
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; }
unset SSH_CONNECTION SSH_CLIENT SSH_TTY TMUX TERM_PROGRAM
TERM=xterm-256color # a real terminal always sets it; CI runners do not
export TERM
HERE=$(cd "$(dirname "$0")" && pwd)
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; /model to change)
send \x04\x04
EOF
printf 'PASS: the first screen names the model and why it was chosen\n'

# A refused key: /model 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 /model to pick another model
send /model\r
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, /model 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 are $ per million tokens in/out
send flash-latest
expect →   good/flash-latest
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'

# ---- the panel during a reply ---------------------------------------------------
# A reply of 40 lines held after its eighth (fake_server's gate) until the script has done with the
# panel, so it is still streaming however slowly the machine runs; /model typed while it streams
# opens the panel at once (nothing is queued). A paste and keys go to the panel's filter
# only; no match says so; Ctrl+C closes it without stopping the reply. Enter on another model says
# the running reply stays on its own and the next message goes to the new one; the reply ends whole,
# and the next request asks for the new model.
{
    printf 'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_long","type":"message","role":"assistant","model":"m","content":[],"stop_reason":null,"usage":{"input_tokens":25,"output_tokens":1}}}\n\n'
    printf 'event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}\n\n'
    n=1
    while [ "$n" -le 40 ]; do
        printf 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"row %02d of the reply\\n"}}\n\n' "$n"
        [ "$n" = 8 ] && wc -c < "$T/long.sse" | tr -d ' ' > "$T/long.gate"
        n=$((n + 1))
    done
    printf 'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n'
    printf 'event: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":99}}\n\n'
    printf 'event: message_stop\ndata: {"type":"message_stop"}\n\n'
} > "$T/long.sse"
plain() { perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\e\][^\a\e]*(\a|\e\\)//g; s/\eO.//g' "$1"; }
mspids=
# mserve NAME SPEC...: a fake server whose models file, $T/NAME.json, has fake/m and fake/other
mserve() {
    name=$1
    shift
    mkdir "$T/log-$name"
    "$SERVER" "$T/port-$name" "$T/log-$name" 300 "$@" &
    mspids="$mspids $!"
    i=0
    while [ ! -s "$T/port-$name" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server $name"; 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}},{"id":"other","name":"Other Model","contextWindow":100000}]}}}' \
        "$(cat "$T/port-$name")" > "$T/$name.json"
}
trap 'cleanup; [ -n "$mspids" ] && kill $mspids 2>/dev/null || :' EXIT HUP INT TERM
# mdrive NAME MODE [COLS ROWS]: pic against server NAME in MODE, the script on stdin
mdrive() {
    FAKE_API_KEY=pic-tui-fake PIC_MODELS_FILE="$T/$1.json" "$DRIVE" "$T/$1.tx" "${3:-120}" "${4:-30}" "$PIC" --tui-mode "$2" \
        --db "$T/j-$1" --workspace "$T/ws" --model fake/m || fail "$1: $(plain "$T/$1.tx" | grep -av '^\s*$' | tail -12)"
}
reqs() { ls "$T/log-$1" | grep -c '\.req$' || true; }
big=$(awk 'BEGIN { while (n++ < 2000) printf "q" }')
for mode in regular fullscreen; do
    mserve "reply-$mode" "gate:$T/long.sse:$(cat "$T/long.gate"):$T/release-$mode" "sse:$S/text.sse"
    mdrive "reply-$mode" "$mode" <<EOF
expect pic fake/m
send \e[O
send go\r
expect row 05
send /model\r
expect Select a model
expect In use now.
send \e[200~$big\e[201~
expect No model matches
send zz\r\r\x7f\x7f\tqq
send \x15
expect type to filter
send \x03
wait 200
send /model\r
expect Select a model
send oth
expect →   fake/other
expect The reply running now stays on fake/m. enter: the next message goes to fake/other
send \r
expect the next message goes to fake/other.
touch $T/release-$mode
expect ↓99
seen reply ready
send Xtyped-later
expect Xtyped-later
send \x15
send next\r
expect Hello
send \x04\x04
expect pic: conversation
EOF
    tx="$T/reply-$mode.tx"
    plain "$tx" | grep -aq 'Operation aborted' && fail "reply $mode: the reply was aborted"
    plain "$tx" | grep -aq 'Stopping' && fail "reply $mode: the reply was stopped"
    plain "$tx" | grep -aq 'Follow-up' && fail "reply $mode: a key or /model was queued"
    [ "$(reqs "reply-$mode")" = 2 ] || fail "reply $mode: $(reqs "reply-$mode") requests, want 2"
    grep -aq '"model":"m"' "$T/log-reply-$mode/1.req" || fail "reply $mode: the first request's model changed"
    grep -aq '"model":"other"' "$T/log-reply-$mode/2.req" || fail "reply $mode: the next request is not on the new model"
    grep -aq qqqq "$T/log-reply-$mode/1.req" && fail "reply $mode: the paste reached the request"
    grep -aq qqqq "$T/log-reply-$mode/2.req" && fail "reply $mode: the paste reached the editor"
    printf 'PASS: %s: /model during a reply opens the panel at once; the reply ends whole and the next request takes the new model\n' "$mode"
done

# The fullscreen frames with the reply streaming behind the box: no clear after the first frame, every
# frame one synchronized update, no row written whose cells did not change.
perl "$HERE/frames.pl" 120 30 < "$T/reply-fullscreen.tx" > "$T/reply.frames" || fail "frames: $(cat "$T/reply.frames")"
grep -aq 'Select a model' "$T/reply-fullscreen.tx" || fail "frames: no box in fullscreen"
printf 'PASS: the panel'"'"'s frames: %s\n' "$(cat "$T/reply.frames")"

# Resizing with the panel open, down to one line and back, leaves what a fresh frame draws. Each
# size waits for its own full repaint (a resize clears the screen once) before the next, so the last
# three repaints are the one after the resizes, the 81-column one and the fresh one, however late
# each comes.
mserve resize "sse:$S/text.sse"
mdrive resize fullscreen 80 24 <<'EOF'
expect pic fake/m
send /model\r
expect Select a model
send \e[B
size 120 36
expectraw \e[2J
size 60 12
expectraw \e[2J
size 30 6
expectraw \e[2J
size 80 24
expectraw \e[2J
size 81 24
expectraw \e[2J
size 80 24
expectraw \e[2J
expect Select a model
send \e
wait 150
send \x04\x04
wait 300
EOF
T=$T perl -e '
    local $/; binmode STDIN; my $t = <STDIN>;
    my $leave = rindex($t, "\e[?1049l"); $t = substr($t, 0, $leave) if $leave > 0;
    my $close = rindex($t, "Select a model");
    my $cut = index($t, "\e[?2026l", $close); $t = substr($t, 0, $cut + 8) if $close > 0 && $cut > 0;
    my @p = split /\e\[2J/, $t, -1;
    die "too few repaints\n" if @p < 4;
    open my $a, ">", "$ENV{T}/r-after.tx" or die; print $a $p[-3]; close $a;
    open my $b, ">", "$ENV{T}/r-fresh.tx" or die; print $b $p[-1]; close $b;
' < "$T/resize.tx" || fail "resize: the transcript"
perl "$HERE/screen.pl" 80 24 < "$T/r-after.tx" > "$T/r-after.screen"
perl "$HERE/screen.pl" 80 24 < "$T/r-fresh.tx" > "$T/r-fresh.screen"
grep -q 'Select a model' "$T/r-after.screen" || fail "resize: no panel on the screen after the resizes"
cmp -s "$T/r-after.screen" "$T/r-fresh.screen" ||
    fail "resize: the screen after resizing differs from a fresh one: $(diff "$T/r-after.screen" "$T/r-fresh.screen" | head -12)"
printf 'PASS: resizing with the panel open, down to one line and back, leaves what a fresh frame draws\n'

# /model NAME: one clear match switches at once, with no panel; several open it on them; none says so
# and stays open through Enter. One Enter on a model the slash menu offers switches to it.
mserve name "sse:$S/text.sse"
mdrive name regular <<'EOF'
expect pic fake/m
send /model oth\r
expect model fake/other
send /model fake\r
expect > fake
expect →   fake/
send \e
wait 200
send /model qqqj\r
expect No model matches "qqqj".
send \r
wait 200
send x
expect > qqqjx
send \e
wait 200
send /model fake/m
expect [fake]
send \r
expect model fake/m
send \x04\x04
EOF
plain "$T/name.tx" | grep -aq '> oth' && fail "name: /model oth opened the panel"
printf 'PASS: /model NAME switches on one clear match, opens the panel on several, and says when none matches\n'

# With nothing typed the picker suggests a short list and ends with how to search the rest: a provider
# of other labs' models (ids with a lab before a slash) shows only its flagships and models used lately.
# After a message to one of its models, that model is under "In use and recent".
mserve suggest "sse:$S/text.sse"
port=$(cat "$T/port-suggest")
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$FAKE_API_KEY","models":[{"id":"m","contextWindow":200000}]},"agg":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$FAKE_API_KEY","models":[{"id":"acme/widget-1","contextWindow":100000},{"id":"acme/widget-2","contextWindow":100000}]}}}' \
    "$port" "$port" > "$T/suggest.json"
mdrive suggest regular <<'EOF'
expect pic fake/m
send /model\r
expect type to search all
send \e
wait 200
send /model acme/widget-1\r
expect model agg/acme/widget-1
send hi\r
expect Hello
send /model\r
expect In use and recent
expect agg/acme/widget-1
send \e
wait 200
send \x04\x04
expect pic: conversation
EOF
first=$(plain "$T/suggest.tx" | awk '/type to search all/ { print; exit } { print }')
printf '%s' "$first" | grep -aq 'acme/widget' && fail "suggest: a model of another lab was suggested before it was used"
plain "$T/suggest.tx" | grep -aq 'acme/widget-2  ' && fail "suggest: an unused model of another lab was suggested"
printf 'PASS: with nothing typed the picker suggests a short list, models used lately first, and says how to search all\n'
