#!/bin/sh
# The terminal's answers and the done signal, on a pseudo-terminal against a
# fake server. pty_drive answers DA1 as every terminal does, and OSC 11 when
# told a background: a light answer picks the light theme (ahead of
# COLORFGBG, never over an explicit theme), no answer reaches the editor as
# text, a terminal that answers nothing still starts. When a turn ends with
# the window unfocused pic sends BEL and OSC 9; not while focused, not after a
# short turn with focus unknown, and not when notifyWhenDone is false.
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-replies.XXXXXX")
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"
export HOME="$T/home" ANTHROPIC_API_KEY=pic-tui-test-key PIC_MODELS_FILE="$T/models.json" PIC_MODEL_CATALOG=offline
export T
export PIC_NO_NATIVE_CLIPBOARD=1
unset COLORFGBG COLORTERM VTE_VERSION
export TERM=xterm-256color
"$SERVER" "$T/port" "$T/log" 120 "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" \
    "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" &
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":"$ANTHROPIC_API_KEY","models":[{"id":"m","contextWindow":200000}]}}}' \
    "$(cat "$T/port")" > "$T/models.json"
drive() { # NAME: run pic (regular mode, truecolor) with the script on stdin; the rest are pic's arguments
    name=$1
    shift
    env COLORTERM=truecolor "COLORFGBG=${FGBG-}" "$DRIVE" "$T/$name.tx" 80 24 "$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 -8)"
}
has() { grep -aqF "$2" "$T/$1.tx"; } # TRANSCRIPT BYTES
sgr() { printf '\033[%sm' "$1"; }
dark_bg=$(sgr '48;2;33;59;73')
light_bg=$(sgr '48;2;223;231;236')
signal=$(printf '\007\033]9;pic: reply ready\033\\')
# FIRST... script lines, then one message; "/name" runs once the request is over, so the signal (if any)
# has been written by the time "named" shows.
say() {
    for l in "$@"; do printf '%s\n' "$l"; done
    printf 'expect pic fake/m\nsend hello\\r\nexpect Hello, "world"\nsend /name x\\r\nexpect named x\nsend \\x04\\x04\nexpect pic: conversation\n'
}

say 'bg rgb:ffff/ffff/ffff' | drive light
has light "$light_bg" || fail "a white background answer did not pick the light theme"
has light "$dark_bg" && fail "light: the dark background appeared"
has light "$(printf '\033]11;?\033\\\033[c')" || fail "the probe (OSC 11 then DA1) was not sent"
grep -aq 'rgb' "$T"/log/*.req && fail "the background answer reached the request as typed text"
has light "$signal" && fail "a short turn with focus unknown sent the done signal"
has light "$(printf '\033[?1004h')" || fail "focus reports were not turned on"
has light "$(printf '\033[?1004l')" || fail "focus reports were not turned off on exit"
printf 'PASS: an OSC 11 answer picks the light theme and is consumed, not typed\n'

FGBG='0;15'
say 'bg rgb:1e1e/1e1e/2e2e' | drive darkwins
has darkwins "$dark_bg" || fail "a dark background answer did not win over COLORFGBG=0;15"
FGBG=''
say 'bg rgb:ffff/ffff/ffff' | drive explicit --theme dark
has explicit "$dark_bg" || fail "--theme dark lost to the terminal's answer"
has explicit "$light_bg" && fail "explicit: the light background appeared"
printf 'PASS: the answer wins over COLORFGBG, never over an explicit theme\n'

t0=$(date +%s)
say 'answer off' | drive silent
t1=$(date +%s)
has silent "$dark_bg" || fail "a terminal that answers nothing did not get the default dark theme"
[ $((t1 - t0)) -lt 15 ] || fail "a terminal that answers nothing slowed the run to $((t1 - t0)) s"
printf 'PASS: a terminal that answers nothing still starts, with the default theme\n'

say 'send \e[O' | drive unfocused
has unfocused "$signal" || fail "unfocused: no BEL and OSC 9 when the turn ended"
say 'send \e[O' 'send \e[I' | drive focused
has focused "$signal" && fail "focused: the done signal was sent while the window had focus"
"$PIC" settings notifyWhenDone false > /dev/null
say 'send \e[O' | drive disabled
has disabled "$signal" && fail "notifyWhenDone false: the done signal was still sent"
has disabled ']9;' && fail "notifyWhenDone false: an OSC 9 was still sent"
printf 'PASS: the done signal goes out when unfocused, not when focused or turned off\n'

# Grapheme clusters (mode 2027) and the kitty keyboard protocol: asked in the probe, switched on only when the
# terminal answers, switched off on exit. Without answers neither is written. With the protocol on, Ctrl+D
# arrives as CSI 100;5u and still quits.
printf 'cluster\nkitty\nexpect pic fake/m\nsend hello\\r\nexpect Hello, "world"\nsend \\e[100;5u\nsend \\e[100;5u\nexpect pic: conversation\n' | drive modes
has modes "$(printf '\033[?2027$p')" || fail "the probe did not ask for mode 2027"
has modes "$(printf '\033[?u')" || fail "the probe did not ask for the kitty keyboard flags"
has modes "$(printf '\033[?2027h')" || fail "mode 2027 was not set after the terminal reported it reset"
has modes "$(printf '\033[>1u')" || fail "the kitty keyboard flags were not pushed after the terminal answered"
has modes "$(printf '\033[?2027l')" || fail "mode 2027 was not put back on exit"
has modes "$(printf '\033[<u')" || fail "the kitty keyboard flags were not popped on exit"
say | drive nomodes
has nomodes "$(printf '\033[?2027h')" && fail "mode 2027 was set though the terminal did not answer"
has nomodes "$(printf '\033[>1u')" && fail "the kitty keyboard flags were pushed though the terminal did not answer"
printf 'PASS: mode 2027 and kitty flag 1 are asked for, set only when answered, put back on exit; Ctrl+D as CSI u quits\n'
