#!/bin/sh
# Pi's print mode: pic -p runs one prompt and prints the answer; piped stdin,
# @files (text and image) and the message make one prompt joined as Pi's
# buildInitialMessage joins them; --system-prompt and --append-system-prompt
# (a file path or text), SYSTEM.md and APPEND_SYSTEM.md shape the system
# prompt; -- ends the options. Request bodies are read from the fake server's log.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-print.XXXXXX")
T=$(cd "$T" && pwd -P)
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME"
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; }
export ANTHROPIC_API_KEY=pic-print-test-key PIC_PI_EXPORT=0 PIC_MODEL_CATALOG=offline
"$PIC" settings cacheRetention none > /dev/null

PNG_B64='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=='
printf '%s' "$PNG_B64" | base64 -d > "$T/dot.png" 2>/dev/null || printf '%s' "$PNG_B64" | base64 -D > "$T/dot.png"

n=0
serve() { # SPEC...: a fresh server, journal and workspace
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    n=$((n + 1))
    mkdir "$T/log$n" "$T/ws$n"
    DB="$T/j$n.sqlite"
    WS="$T/ws$n"
    LOG="$T/log$n"
    "$SERVER" "$T/port$n" "$LOG" 60 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port$n" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "server did not start"
        sleep 0.05
    done
    port=$(cat "$T/port$n")
    printf '{"providers":{"va":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"see","input":["text","image"]}]}}}' \
        "$port" > "$T/models$n.json"
    export PIC_MODELS_FILE="$T/models$n.json"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" --model va/see "$@"; }
has() { grep -qF -- "$2" "$1" || fail "$3: $(grep -o '"system".*\|"messages".*' "$1" | cut -c1-500)"; }
hasnt() { ! grep -qF -- "$2" "$1" || fail "$3"; }

# -p TEXT: the answer on stdout, exit 0, the text as the user message.
serve "sse:$S/text.sse"
pic -p 'what is this' < /dev/null > "$T/out" 2> "$T/err" || fail "-p: $(cat "$T/err")"
[ -s "$T/out" ] || fail "-p: no answer"
has "$LOG/1.req" '"messages":[{"role":"user","content":"what is this"}]' "-p: user message"
has "$LOG/1.req" 'You are a coding assistant running inside pic' "-p: default system prompt"
has "$LOG/1.req" 'pic help TOPIC' "-p: system prompt points to pic help"
# pic ask is unchanged.
serve "sse:$S/text.sse"
pic ask 'plain ask' > "$T/ask.out" 2>&1 || fail "ask: $(cat "$T/ask.out")"
has "$LOG/1.req" '"content":"plain ask"' "ask: user message"

# --print, with the message after the flag or after the options.
serve "sse:$S/text.sse"
pic --print < /dev/null 'long form' > /dev/null 2>&1 || fail "--print"
has "$LOG/1.req" '"content":"long form"' "--print: message"

# Piped stdin: trimmed, then the message, no separator (Pi's buildInitialMessage).
serve "sse:$S/text.sse"
printf 'line one\nline two\n\n' | pic -p ' review this' > /dev/null 2>&1 || fail "stdin"
has "$LOG/1.req" '"content":"line one\nline two review this"' "stdin: prepended without a separator"
serve "sse:$S/text.sse"
printf 'only stdin\n' | pic -p > /dev/null 2>&1 || fail "stdin alone"
has "$LOG/1.req" '"content":"only stdin"' "stdin alone is the prompt"
serve "sse:$S/text.sse"
printf '  \n' | pic -p 'blank stdin' > /dev/null 2>&1 || fail "blank stdin"
has "$LOG/1.req" '"content":"blank stdin"' "whitespace-only stdin is ignored"

# @file: text as <file name="ABS">, newline, content, newline, </file>, then the message.
serve "sse:$S/text.sse"
printf 'alpha\nbeta\n' > "$WS/notes.md"
pic -p @notes.md 'summarize' < /dev/null > /dev/null 2>&1 || fail "@file"
has "$LOG/1.req" '"content":"<file name=\"'"$WS"'/notes.md\">\nalpha\nbeta\n\n</file>\nsummarize"' "@file: tagged text"
# stdin, two files and the message, in Pi's order.
serve "sse:$S/text.sse"
printf 'A\n' > "$WS/a.txt"
printf 'B' > "$WS/b.txt"
: > "$WS/empty.txt"
printf 'piped' | pic -p @a.txt @empty.txt @b.txt 'go' > /dev/null 2>&1 || fail "stdin and files"
has "$LOG/1.req" '"content":"piped<file name=\"'"$WS"'/a.txt\">\nA\n\n</file>\n<file name=\"'"$WS"'/b.txt\">\nB\n</file>\ngo"' "stdin, files, message"
# An image: the empty tag in the text and the image attached.
serve "sse:$S/text.sse"
cp "$T/dot.png" "$WS/dot.png"
pic -p @dot.png 'what is this' < /dev/null > /dev/null 2>&1 || fail "@image"
has "$LOG/1.req" '"text":"<file name=\"'"$WS"'/dot.png\"></file>\nwhat is this"}' "@image: empty tag"
has "$LOG/1.req" '{"type":"image","source":{"type":"base64","media_type":"image/png","data":"'"$PNG_B64"'"}}' "@image: attached"

# An unreadable @file: Pi's error, exit 1, nothing sent.
serve "sse:$S/text.sse"
rc=0
pic -p @missing.txt 'x' < /dev/null > "$T/out" 2> "$T/err" || rc=$?
[ "$rc" = 1 ] || fail "missing @file: exit $rc"
grep -qF "Error: File not found: $WS/missing.txt" "$T/err" || fail "missing @file: $(cat "$T/err")"
[ ! -e "$LOG/1.req" ] || fail "missing @file: a request was sent"
printf 'secret' > "$WS/locked.txt"
chmod 000 "$WS/locked.txt"
if [ "$(id -u)" != 0 ]; then
    rc=0
    pic -p @locked.txt 'x' < /dev/null > /dev/null 2> "$T/err" || rc=$?
    [ "$rc" = 1 ] || fail "unreadable @file: exit $rc"
    grep -qF "Error: Could not read file $WS/locked.txt" "$T/err" || fail "unreadable @file: $(cat "$T/err")"
    [ ! -e "$LOG/1.req" ] || fail "unreadable @file: a request was sent"
fi

# --system-prompt replaces the prompt (text, or a file); --append-system-prompt adds an addendum.
serve "sse:$S/text.sse"
pic --system-prompt 'You are terse.' -p 'hi' < /dev/null > /dev/null 2>&1 || fail "--system-prompt"
has "$LOG/1.req" '"system":[{"type":"text","text":"You are terse.' "--system-prompt: replaced"
hasnt "$LOG/1.req" 'running inside pic' "--system-prompt: default kept"
hasnt "$LOG/1.req" '<tools>' "--system-prompt: tools section kept"
serve "sse:$S/text.sse"
printf 'From a file.\n' > "$T/sys.txt"
pic --system-prompt "$T/sys.txt" -p 'hi' < /dev/null > /dev/null 2>&1 || fail "--system-prompt file"
has "$LOG/1.req" '"system":[{"type":"text","text":"From a file.\n' "--system-prompt FILE: read"
hasnt "$LOG/1.req" 'sys.txt' "--system-prompt FILE: path leaked"
serve "sse:$S/text.sse"
printf 'Second from file.\n' > "$T/more.txt"
pic --append-system-prompt 'Be brief.' --append-system-prompt "$T/more.txt" -p 'hi' < /dev/null > /dev/null 2>&1 || fail "--append-system-prompt"
has "$LOG/1.req" 'You are a coding assistant running inside pic' "--append-system-prompt: default kept"
has "$LOG/1.req" '<addendum>\nBe brief.\n\nSecond from file.\n\n</addendum>' "--append-system-prompt: addendum"
# ask takes them too.
serve "sse:$S/text.sse"
pic --system-prompt 'ask prompt' ask 'hi' > /dev/null 2>&1 || fail "ask --system-prompt"
has "$LOG/1.req" '"system":[{"type":"text","text":"ask prompt' "ask: --system-prompt"

# SYSTEM.md and APPEND_SYSTEM.md: global in ~/.pic, the workspace's only when trusted; the flags win.
serve "sse:$S/text.sse"
mkdir -p "$HOME/.pic" "$WS/.pic"
printf 'Global system.' > "$HOME/.pic/SYSTEM.md"
printf 'Global append.' > "$HOME/.pic/APPEND_SYSTEM.md"
printf 'Project system.' > "$WS/.pic/SYSTEM.md"
printf 'Project append.' > "$WS/.pic/APPEND_SYSTEM.md"
pic -p 'hi' < /dev/null > /dev/null 2>&1 || fail "SYSTEM.md untrusted"
has "$LOG/1.req" '"system":[{"type":"text","text":"Global system.' "untrusted workspace: global SYSTEM.md"
has "$LOG/1.req" '<addendum>\nGlobal append.\n</addendum>' "untrusted workspace: global APPEND_SYSTEM.md"
hasnt "$LOG/1.req" 'Project' "untrusted workspace: project files read"
serve "sse:$S/text.sse"
mkdir -p "$WS/.pic"
printf 'Project system.' > "$WS/.pic/SYSTEM.md"
printf 'Project append.' > "$WS/.pic/APPEND_SYSTEM.md"
"$PIC" --workspace "$WS" trust yes > /dev/null || fail "trust yes"
pic -p 'hi' < /dev/null > /dev/null 2>&1 || fail "SYSTEM.md trusted"
has "$LOG/1.req" '"system":[{"type":"text","text":"Project system.' "trusted workspace: project SYSTEM.md"
has "$LOG/1.req" '<addendum>\nProject append.\n</addendum>' "trusted workspace: project APPEND_SYSTEM.md"
hasnt "$LOG/1.req" 'Global' "trusted workspace: global file read too"
serve "sse:$S/text.sse"
mkdir -p "$WS/.pic"
printf 'Project system.' > "$WS/.pic/SYSTEM.md"
"$PIC" --workspace "$WS" trust yes > /dev/null
pic --system-prompt 'flag wins' -p 'hi' < /dev/null > /dev/null 2>&1 || fail "flag over SYSTEM.md"
has "$LOG/1.req" '"system":[{"type":"text","text":"flag wins' "--system-prompt over SYSTEM.md"
rm -f "$HOME/.pic/SYSTEM.md" "$HOME/.pic/APPEND_SYSTEM.md"

# --: what follows is messages and files, even with a leading dash or @.
serve "sse:$S/text.sse"
pic -p -- '- summarize these' < /dev/null > /dev/null 2>&1 || fail "--"
has "$LOG/1.req" '"content":"- summarize these"' "--: dash message"
serve "sse:$S/text.sse"
printf 'A\n' > "$WS/a.txt"
pic -p -- @a.txt 'then' < /dev/null > /dev/null 2>&1 || fail "-- @file"
has "$LOG/1.req" '"content":"<file name=\"'"$WS"'/a.txt\">\nA\n\n</file>\nthen"' "--: @file still a file"

# -p with --json: Pi's JSON events on stdout.
serve "sse:$S/text.sse"
pic --json -p 'events' < /dev/null > "$T/out" 2> /dev/null || fail "--json -p"
grep -q '"type":"agent_end"' "$T/out" || fail "--json -p: no agent_end: $(head -c 300 "$T/out")"

# -p --session ID and -c continue a conversation; an unknown ID admits nothing.
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse"
pic -p 'first' < /dev/null > /dev/null 2>&1 || fail "continue: first"
id=$(pic sessions | awk '{print $1; exit}')
[ -n "$id" ] || fail "continue: no session"
pic --session "$id" -p 'second' < /dev/null > /dev/null 2> "$T/err" || fail "--session -p: $(cat "$T/err")"
pic -p --session "$id" 'third' < /dev/null > /dev/null 2> "$T/err" || fail "-p --session: $(cat "$T/err")"
[ "$(pic sessions | wc -l | tr -d ' ')" = 1 ] || fail "--session -p: started a new conversation"
for w in first second third; do pic dump | grep -q "user | $w\$" || fail "continue: $w not in the conversation"; done
has "$LOG/3.req" '"content":"first"' "--session: earlier turn sent"
serve "sse:$S/text.sse" "sse:$S/text.sse"
pic -p 'one' < /dev/null > /dev/null 2>&1 || fail "-c: first"
pic -c -p 'two' < /dev/null > /dev/null 2> "$T/err" || fail "-c -p: $(cat "$T/err")"
pic -p --continue 'three' < /dev/null > /dev/null 2> "$T/err" || fail "-p --continue: $(cat "$T/err")"
[ "$(pic sessions | wc -l | tr -d ' ')" = 1 ] || fail "-c: started a new conversation"
has "$LOG/2.req" '"content":"one"' "-c: earlier turn sent"
before=$(pic dump | wc -l)
rc=0
pic --session nosuch -p 'lost' < /dev/null > /dev/null 2> "$T/err" || rc=$?
[ "$rc" != 0 ] || fail "unknown ID: exit 0"
grep -q 'no session nosuch' "$T/err" || fail "unknown ID: message: $(cat "$T/err")"
[ "$(pic dump | wc -l)" = "$before" ] || fail "unknown ID: admitted something"
serve "sse:$S/text.sse"
rc=0
pic -c -p 'empty' < /dev/null > /dev/null 2> "$T/err" || rc=$?
[ "$rc" != 0 ] || fail "-c with no session: exit 0"

# --session-id ID: Pi's "use the session with this ID, creating it otherwise".
serve "sse:$S/text.sse" "sse:$S/text.sse"
pic --session-id my-run.1 -p 'one' < /dev/null > /dev/null 2> "$T/err" || fail "--session-id new: $(cat "$T/err")"
pic sessions | grep -q '^my-run.1 ' || fail "--session-id: not created under that ID: $(pic sessions)"
pic -p --session-id my-run.1 'two' < /dev/null > /dev/null 2> "$T/err" || fail "--session-id existing: $(cat "$T/err")"
[ "$(pic sessions | wc -l | tr -d ' ')" = 1 ] || fail "--session-id: the second run made a new conversation"
has "$LOG/2.req" '"content":"one"' "--session-id: earlier turn sent"
rc=0
pic --session-id my-run.1 -c -p 'x' < /dev/null > /dev/null 2> "$T/err" || rc=$?
[ "$rc" != 0 ] && grep -q -- '--session-id cannot be combined with --continue' "$T/err" || fail "--session-id with -c: $rc $(cat "$T/err")"
rc=0
pic --session-id 'bad_' -p 'x' < /dev/null > /dev/null 2> "$T/err" || rc=$?
[ "$rc" != 0 ] && grep -q 'Session id must be' "$T/err" || fail "--session-id invalid: $rc $(cat "$T/err")"
printf 'PASS: --session-id names a new conversation or joins the one with that ID\n'

# --no-session: a throwaway journal, gone at exit; nothing is kept in --db or the workspace.
serve "sse:$S/text.sse"
mkdir "$T/tmp$n"
TMPDIR="$T/tmp$n" pic --no-session -p 'ephemeral' < /dev/null > "$T/out" 2> "$T/err" || fail "--no-session: $(cat "$T/err")"
[ -s "$T/out" ] || fail "--no-session: no answer"
has "$LOG/1.req" '"content":"ephemeral"' "--no-session: user message"
[ ! -e "$DB" ] || fail "--no-session: wrote the journal"
[ ! -e "$WS/.pic" ] || fail "--no-session: made .pic in the workspace"
[ -z "$(ls -A "$T/tmp$n")" ] || fail "--no-session: left $(ls "$T/tmp$n")"
rc=0
pic --no-session -r -p 'x' < /dev/null > /dev/null 2> "$T/err" || rc=$?
[ "$rc" = 0 ] || fail "--no-session -r: $(cat "$T/err")"
printf 'PASS: --no-session keeps nothing\n'

# --mode json is -p with Pi's JSON events; --mode text is the default; others are refused.
serve "sse:$S/text.sse" "sse:$S/text.sse"
pic --mode json 'as json' < /dev/null > "$T/out" 2> "$T/err" || fail "--mode json: $(cat "$T/err")"
grep -q '"type":"agent_end"' "$T/out" || fail "--mode json: no agent_end: $(head -c 300 "$T/out")"
pic --mode text -p 'as text' < /dev/null > "$T/out" 2> "$T/err" || fail "--mode text: $(cat "$T/err")"
grep -q '"type"' "$T/out" && fail "--mode text printed JSON"
rc=0
pic --mode bogus -p x < /dev/null > /dev/null 2> "$T/err" || rc=$?
[ "$rc" = 2 ] && grep -q 'Invalid mode "bogus". Valid values: text, json, rpc' "$T/err" || fail "--mode bogus: $rc $(cat "$T/err")"
printf 'PASS: --mode json and text\n'

# -r / --resume picks a conversation in the terminal interface; with -p there is nothing to pick.
rc=0
pic -r -p 'x' < /dev/null > /dev/null 2> "$T/err" || rc=$?
[ "$rc" = 2 ] && grep -q -- '--resume picks a conversation in the terminal' "$T/err" || fail "-r -p: $rc $(cat "$T/err")"
if [ -n "${DRIVE:-}" ]; then
    serve "sse:$S/text.sse"
    pic -p 'picked one' < /dev/null > /dev/null 2>&1 || fail "resume: first"
    "$DRIVE" "$T/resume.tx" 100 30 "$PIC" --tui-mode regular --db "$DB" --workspace "$WS" --model va/see --resume <<'EOF2' ||
expect Resume a conversation
expect picked one
send \x1b
send \x04\x04
EOF2
        fail "-r: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/resume.tx" | grep -v '^\s*$' | tail -8)"
    printf 'PASS: -r opens the conversation picker\n'
    pic --session-id tui-id.1 -p 'seen again' < /dev/null > /dev/null 2>&1 || fail "--session-id tui: first"
    "$DRIVE" "$T/sid.tx" 100 30 "$PIC" --tui-mode regular --db "$DB" --workspace "$WS" --model va/see --session-id tui-id.1 <<'EOF2' ||
expect seen again
send \x04\x04
EOF2
        fail "--session-id tui: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/sid.tx" | grep -v '^\s*$' | tail -8)"
    printf 'PASS: --session-id resumes that conversation in the terminal\n'
fi

# An unknown option is a usage error, exit 2, before any journal is made.
rc=0
"$PIC" -p --nonsense < /dev/null > /dev/null 2>&1 || rc=$?
[ "$rc" = 2 ] || fail "unknown option: exit $rc"

printf 'PASS\n'
