#!/bin/sh
# The settings panel (docs/manual/settings.md) on a pseudo-terminal against a
# fake server: it opens at any time, a running reply or tool included, without
# interrupting it; it takes every key while open and gives back exactly what
# was under it; its fields cannot save a bad value; a change made elsewhere
# shows within a second. MODE (regular, the default, or fullscreen) is the
# first argument; --no-faults, which the release run passes, is accepted.
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}
MODE=regular
for arg in "$@"; do
    case $arg in regular | fullscreen) MODE=$arg ;; esac
done
S=$(cd "$(dirname "$0")/../pic/streams" && pwd)
V=$(cd "$(dirname "$0")/streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-settings.XXXXXX")
spids=
rpids=
cleanup() { [ -n "$spids$rpids" ] && kill $spids $rpids 2>/dev/null || :; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
mkdir "$T/home"
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 HOME="$T/home" ANTHROPIC_API_KEY=pic-settings-test-key PIC_MODEL_CATALOG=offline PIC_NO_NATIVE_CLIPBOARD=1
F2='\eOQ'
DRIVE_ENV=

# serve NAME SPEC...: a fake server whose models file is $T/NAME.json
serve() {
    name=$1
    shift
    mkdir "$T/log-$name" "$T/ws-$name"
    "$SERVER" "$T/port-$name" "$T/log-$name" 300 "$@" &
    spids="$spids $!"
    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":"$ANTHROPIC_API_KEY","models":[{"id":"m","contextWindow":200000}]}}}' \
        "$(cat "$T/port-$name")" > "$T/$name.json"
}
# drive NAME [COLS ROWS]: pic against server NAME in MODE, the script on stdin
drive() {
    name=$1
    cols=${2:-80}
    rows=${3:-24}
    env $DRIVE_ENV PIC_MODELS_FILE="$T/$name.json" "$DRIVE" "$T/$name.tx" "$cols" "$rows" "$PIC" --tui-mode "$MODE" --db "$T/j-$name" \
        --workspace "$T/ws-$name" --model fake/m ||
        fail "$name: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$name.tx" | grep -av '^\s*$' | tail -8)"
}
plain() { perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\e\][^\a\e]*(\a|\e\\)//g; s/\eO.//g' "$1"; }
reqs() { ls "$T/log-$1" | grep -c '\.req$' || true; }
# when FILE PATTERN COMMAND...: runs COMMAND once PATTERN is in FILE (gives up after 30 s)
when() {
    file=$1
    pat=$2
    shift 2
    (
        n=0
        until grep -aqF -- "$pat" "$file" 2>/dev/null; do
            n=$((n + 1))
            [ "$n" -lt 600 ] || exit 0
            sleep 0.05
        done
        "$@"
    ) &
    rpids="$rpids $!"
}
setting() { "$PIC" settings "$1"; }
# the reply was not cut short: no abort, no stop, and its end arrived
whole() {
    plain "$T/$1.tx" | grep -aq 'Operation aborted' && fail "$1: the reply was aborted"
    plain "$T/$1.tx" | grep -aq 'Stopping' && fail "$1: the reply was stopped"
    [ "$(reqs "$1")" = "${2:-1}" ] || fail "$1: $(reqs "$1") requests, want ${2:-1}"
}

# A reply of 40 lines, one text delta each, sent slowly.
{
    cat <<'EOF'
event: message_start
data: {"type":"message_start","message":{"id":"msg_long","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"usage":{"input_tokens":25,"output_tokens":1}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}

EOF
    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=$((n + 1))
    done
    cat <<'EOF'
event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":99}}

event: message_stop
data: {"type":"message_stop"}

EOF
} > "$T/long.sse"

# ---- A. during a reply --------------------------------------------------------
# F2 while the reply streams: the panel is on screen, the reply's last words
# still arrive, and the server saw one whole request and no cancel. Then with
# TERM unset and LC_ALL=C, as the forge runs.
case_a() {
    serve "$1" "slow:$T/long.sse:60"
    drive "$1" <<EOF
expect pic fake/m
send go\r
expect row 05
send $F2
expect type to filter
expect Default model
expect row 40
expect ↓99
send \e
wait 150
send Xtyped-later
expect Xtyped-later
send \x15
send \x04\x04
expect pic: conversation
EOF
    whole "$1"
}
DRIVE_ENV=
case_a a
printf 'PASS: A. %s: the panel opens during a reply, which finishes whole\n' "$MODE"
DRIVE_ENV="-u TERM LC_ALL=C"
case_a a-noterm
DRIVE_ENV=
printf 'PASS: A. %s: with TERM unset and LC_ALL=C the panel draws and closes\n' "$MODE"

# ---- B. during a tool ---------------------------------------------------------
# The panel opens while a bash call waits; its output appears and the reply ends.
serve b "sse:$V/bash_live.sse" "sse:$V/done.sse"
when "$T/b.tx" "type to filter" touch "$T/ws-b/live-release"
drive b <<EOF
expect pic fake/m
send go\r
expect out-alpha
send $F2
expect type to filter
expect out-beta
expect All done.
send \e
wait 150
send \x04\x04
expect pic: conversation
EOF
whole b 2
printf 'PASS: B. %s: a tool call runs on behind the panel\n' "$MODE"

# ---- C. editor text ---------------------------------------------------------------
# Half a message, the cursor three back; open, change a setting, close: the same
# text and cursor (X lands there), and Enter sends it whole.
serve c "sse:$S/text.sse"
drive c <<EOF
expect pic fake/m
send half a message
send \e[D\e[D\e[D
send $F2
expect type to filter
send hyper
expect → Hyperlinks
send \e[C
expect ✓ on
send \e
wait 150
send \e
wait 150
send X
expect messXage
send \r
expect Hello
send \x04\x04
expect pic: conversation
EOF
grep -aq 'half a messXage' "$T/log-c/1.req" || fail "C: the message sent was not the one typed"
[ "$(setting hyperlinks)" = on ] || fail "C: hyperlinks is $(setting hyperlinks)"
"$PIC" settings --unset hyperlinks
printf 'PASS: C. %s: the editor keeps its text and cursor under the panel\n' "$MODE"

# ---- D. over a picker and a prompt ------------------------------------------------------
# The model picker with a filter and the trust prompt moved down come back as they were.
serve d "sse:$S/text.sse"
drive d <<EOF
expect pic fake/m
send /model\r
expect Select a model
send fak
expect > fak
send $F2
expect type to filter
send \e
wait 150
expect > fak
send \e
wait 150
send /trust\r
expect Workspace trust
send \e[B
expect →   Do not trust this workspace
send $F2
expect type to filter
send \e
wait 150
expect →   Do not trust this workspace
send \e
wait 150
send \x04\x04
EOF
printf 'PASS: D. %s: a picker and a prompt under the panel come back as they were\n' "$MODE"

# ---- E. /settings during a reply ------------------------------------------------------
# It opens at once; nothing is queued, and no second request follows.
serve e "slow:$T/long.sse:60" "sse:$S/text.sse"
drive e <<EOF
expect pic fake/m
send go\r
expect row 05
send /settings\r
expect type to filter
expect ↓99
send \e
wait 150
send \x04\x04
expect pic: conversation
EOF
plain "$T/e.tx" | grep -aq 'Follow-up: /settings' && fail "E: /settings was queued"
whole e
printf 'PASS: E. %s: /settings during a reply opens at once and queues nothing\n' "$MODE"

# ---- F. input -----------------------------------------------------------------------
# A 2000-character paste and a burst of keys with the panel open reach neither
# the editor nor the request; Ctrl+C and Esc close it and the reply runs on.
serve f "slow:$T/long.sse:60" "sse:$S/text.sse"
big=$(awk 'BEGIN { while (n++ < 2000) printf "q" }')
drive f <<EOF
expect pic fake/m
send go\r
expect row 05
send $F2
expect type to filter
send \e[200~$big\e[201~
expect No setting matches
send zz\r\r\x7f\x7f\tqq
send \x15
expect type to filter
send \x03
wait 150
send $F2
expect type to filter
send \e
wait 150
expect ↓99
send Xtyped-later
expect Xtyped-later
send \x15
send \x04\x04
expect pic: conversation
EOF
whole f
grep -aq qqqq "$T/log-f/1.req" && fail "F: the paste reached the request"
plain "$T/f.tx" | grep -aq 'Follow-up' && fail "F: a key was queued"
printf 'PASS: F. %s: keys and pastes go to the panel only; Ctrl+C and Esc close it\n' "$MODE"

# ---- G. values ------------------------------------------------------------------------
# A number field ignores letters and saves only in its range; a choice cycles
# through exactly its list; Ctrl+R puts the default back.
serve g "sse:$S/text.sse"
drive g <<EOF
expect pic fake/m
send $F2
expect type to filter
send lapse after
expect → Lapse after
send \r
expect Seconds:
send x0
expect at least 1
send \r
wait 200
send \x7f90\r
expect 90 seconds
send \x15
send hyperlinks
expect → Hyperlinks
send \e[C
expect ✓ on
send \e[C
expect ✓ off
send \e[C
expect ✓ auto
send \e[C
expect ✓ on
send \x12
expect ✓ auto
send \e
wait 150
send \e
wait 150
send \x04\x04
EOF
[ "$(setting lapseSeconds)" = 90 ] || fail "G: lapseSeconds is '$(setting lapseSeconds)', want 90"
[ -z "$(setting hyperlinks)" ] || fail "G: hyperlinks is '$(setting hyperlinks)' after Ctrl+R"
"$PIC" settings --unset lapseSeconds
printf 'PASS: G. %s: fields refuse bad values, choices cycle, Ctrl+R restores the default\n' "$MODE"

# ---- H. changed elsewhere -------------------------------------------------------------
# pic settings and an RPC set_setting change values under the open panel; the
# rows show them, and an open field keeps its text.
serve h "sse:$S/text.sse"
when "$T/h.tx" "✓ auto" "$PIC" settings hyperlinks off
when "$T/h.tx" "Tokens: 77" sh -c "printf '%s\n' '{\"id\":\"s\",\"type\":\"set_setting\",\"key\":\"compaction.reserveTokens\",\"value\":\"4096\"}' |
    PIC_MODELS_FILE='$T/h.json' '$PIC' --mode rpc --db '$T/j-h2' --workspace '$T/ws-h' --model fake/m > '$T/h-rpc.out' 2>&1"
drive h <<EOF
expect pic fake/m
send $F2
expect type to filter
send hyperlinks
expect ✓ auto
expect ✓ off
send \x15
send reserve
expect → Compaction reserve
send \r
send \x15
send 77
expect → Compaction reserve         4096 tokens
expect changed elsewhere to 4096 tokens
send 8
expect Tokens: 778
send \e
wait 150
send \e
wait 150
send \e
wait 150
send \x04\x04
EOF
grep -aq '"success":true' "$T/h-rpc.out" || fail "H: set_setting over RPC: $(cat "$T/h-rpc.out")"
[ "$(setting compaction.reserveTokens)" = 4096 ] || fail "H: reserveTokens is $(setting compaction.reserveTokens)"
printf 'PASS: H. %s: changes made elsewhere show in the open panel\n' "$MODE"
