#!/bin/sh
# Live events: --json writes Pi's JSON-mode events as the run goes (deltas
# from each adapter, tool calls, turns, a cut stream ended as an error and
# retried); --stream writes the reply text as it arrives, once, with tool
# calls on stderr.
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-events.XXXXXX")
# 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-events-test-key OPENROUTER_API_KEY=pic-events-test-key OPENAI_API_KEY=pic-events-test-key
WS="$T/ws"
mkdir "$WS"
n=0
serve() { # SPEC...: a fresh server and journal
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    n=$((n + 1))
    mkdir "$T/log$n"
    DB="$T/j$n.sqlite"
    "$SERVER" "$T/port$n" "$T/log$n" 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
    URL="http://127.0.0.1:$(cat "$T/port$n")/v1/messages"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
types() { sed 's/^{"type":"\([a-z_]*\)".*/\1/' "$1" | tr '\n' ' '; }

# A tool turn, then the answer, as Pi's JSON mode reports them.
serve "sse:$S/thinking_tool.sse" "sse:$S/text.sse"
pic submit k1 'write it' > /dev/null
pic --json run --model anthropic/m --api-url "$URL" > "$T/a.jsonl" 2> "$T/err" || fail "json run: $(cat "$T/err")"
want="agent_start message_start message_end entry_appended turn_start message_start message_update message_end entry_appended tool_execution_start tool_execution_end entry_appended turn_end turn_start message_start message_update message_update message_end entry_appended turn_end agent_end "
[ "$(types "$T/a.jsonl")" = "$want" ] || fail "json: event order: $(types "$T/a.jsonl")"
# Each line is JSON.
while IFS= read -r line; do
    [ "$(sqlite3 :memory: "SELECT json_valid('$(printf '%s' "$line" | sed "s/'/''/g")')")" = 1 ] || fail "json: invalid line: $line"
done < "$T/a.jsonl"
grep -q '"type":"auto_retry_end"' "$T/a.jsonl" && fail "json: auto_retry_end without retry"
eids=$(grep '"type":"entry_appended"' "$T/a.jsonl" | sed 's/.*"entry":{"type":"[^"]*","id":"\([0-9]*\)".*/\1/' | tr '\n' ' ')
[ "$eids" = "1 2 3 4 " ] || fail "json: entry_appended ids: $eids"
grep -q '"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":"Write it."}' "$T/a.jsonl" || fail "json: thinking delta"
grep -q '"type":"tool_execution_start","toolCallId":"[^"]*","toolName":"write","args":{"path":"t.txt","content":"x"}}' "$T/a.jsonl" ||
    fail "json: tool start"
grep -q '"isError":false}' "$T/a.jsonl" || fail "json: tool end"
grep -q '"type":"message_end","message":{"role":"assistant","content":\[{"type":"text","text":"Hello, \\"world\\"\\n"}\],"stopReason":"stop","provider":"anthropic"' "$T/a.jsonl" ||
    fail "json: message end"
grep -q '"type":"agent_end","messages":\[\],"request":"k1","status":"answered"}' "$T/a.jsonl" || fail "json: agent end"
printf 'PASS: --json reports a run with Pi'"'"'s events and entry_appended, in order\n'

# Deltas from the Chat and Responses adapters too.
serve "sse:$here/chat-streams/reasoning_content.sse"
pic submit c1 'think' > /dev/null
pic --json run --model openrouter/test/model --api-url "$URL" > "$T/c.jsonl" 2> "$T/err" || fail "chat: $(cat "$T/err")"
grep -q '"type":"thinking_delta"' "$T/c.jsonl" && grep -q '"type":"text_delta"' "$T/c.jsonl" || fail "chat: deltas"
serve "sse:$here/responses-streams/reasoning_text.sse"
pic submit r1 'think' > /dev/null
pic --json run --model openai/test-model --api-url "$URL" > "$T/r.jsonl" 2> "$T/err" || fail "responses: $(cat "$T/err")"
grep -q '"type":"text_delta"' "$T/r.jsonl" || fail "responses: text delta"
printf 'PASS: every adapter streams text and thinking deltas\n'

# Text mode: the reply streams once; tool calls go to stderr.
serve "sse:$S/thinking_tool.sse" "sse:$S/text.sse"
pic submit t1 'write it' > /dev/null
pic --stream run --model anthropic/m --api-url "$URL" > "$T/out" 2> "$T/err" || fail "stream: $(cat "$T/err")"
[ "$(cat "$T/out")" = 'Hello, "world"' ] || fail "stream: stdout: $(cat "$T/out")"
grep -q '^-> write t.txt$' "$T/err" || fail "stream: tool line: $(cat "$T/err")"
printf 'PASS: --stream writes the reply once as it arrives, tool calls on stderr\n'

# A stream cut mid-reply ends that message as an error, then is retried.
serve "cut:$S/text.sse:420" "sse:$S/text.sse"
pic submit x1 'hello' > /dev/null
pic --json run --model anthropic/m --api-url "$URL" > "$T/x.jsonl" 2> "$T/err" || fail "cut: $(cat "$T/err")"
grep -q '"stopReason":"error","errorMessage":' "$T/x.jsonl" || fail "cut: no error message_end: $(types "$T/x.jsonl")"
grep -q '"type":"auto_retry_start","attempt":2,"maxAttempts":3' "$T/x.jsonl" || fail "cut: no retry"
grep -qxF '{"type":"auto_retry_end","success":true,"attempt":2}' "$T/x.jsonl" || fail "cut: no retry end: $(grep auto_retry "$T/x.jsonl")"
rs=$(grep -n '"type":"auto_retry_start"' "$T/x.jsonl" | head -1 | cut -d: -f1)
re=$(grep -n '"type":"auto_retry_end"' "$T/x.jsonl" | head -1 | cut -d: -f1)
[ "$rs" -lt "$re" ] || fail "cut: auto_retry_end before start"
tail -1 "$T/x.jsonl" | grep -q '"status":"answered"' || fail "cut: not answered"
pic check > /dev/null || fail "cut: integrity"
printf 'PASS: a cut stream ends in an error message, retries, and emits auto_retry_end\n'

# A transport retry reports the real wait before it, and auto_retry_end on success.
serve "retry:503:1" "sse:$S/text.sse"
pic submit w1 'hello' > /dev/null
pic --json run --model anthropic/m --api-url "$URL" > "$T/w.jsonl" 2> "$T/err" || fail "backoff: $(cat "$T/err")"
grep -q '"type":"auto_retry_start","attempt":2,"maxAttempts":4,"delayMs":1000,"errorMessage":"HTTP 503' "$T/w.jsonl" ||
    fail "backoff: $(grep auto_retry "$T/w.jsonl")"
grep -qxF '{"type":"auto_retry_end","success":true,"attempt":2}' "$T/w.jsonl" ||
    fail "backoff: no auto_retry_end: $(grep auto_retry "$T/w.jsonl")"
printf 'PASS: auto_retry_start carries the backoff it is about to wait and ends with auto_retry_end\n'

# Stop during the wait before a retry: no further try is made and auto_retry_end closes the retry.
serve "retry:503:3" "retry:503:3" "retry:503:3" "retry:503:3"
pic submit s1 'hello' > /dev/null
perl -e '$SIG{INT} = "DEFAULT"; exec @ARGV' "$PIC" --db "$DB" --workspace "$WS" --json run --model anthropic/m --api-url "$URL" > "$T/s.jsonl" 2> "$T/err" &
rpid=$!
i=0
until grep -q '"type":"auto_retry_start"' "$T/s.jsonl"; do
    i=$((i + 1))
    [ "$i" -lt 200 ] || fail "stop: no retry wait began"
    sleep 0.05
done
kill -INT "$rpid"
wait "$rpid" || :
[ "$(grep -c '"type":"auto_retry_start"' "$T/s.jsonl")" = 1 ] || fail "stop: retried after stop: $(grep auto_retry "$T/s.jsonl")"
grep -qxF '{"type":"auto_retry_end","success":false,"attempt":2,"finalError":"Retry cancelled"}' "$T/s.jsonl" ||
    fail "stop: no cancelled auto_retry_end: $(grep auto_retry "$T/s.jsonl")"
[ "$(ls "$T/log$n" | grep -c '\.req$')" = 1 ] || fail "stop: $(ls "$T/log$n" | grep -c '\.req$') requests"
printf 'PASS: Stop during a retry wait ends the retries with auto_retry_end\n'

# Exhausted retries emit auto_retry_end with success:false and finalError; a non-retryable error emits none.
serve "cut:$S/text.sse:420" "cut:$S/text.sse:420" "cut:$S/text.sse:420"
pic submit e1 'exhaust' > /dev/null
if pic --json run --model anthropic/m --api-url "$URL" > "$T/e.jsonl" 2> "$T/err"; then
    fail "exhaust: succeeded unexpectedly"
fi
[ "$(grep -c '"type":"auto_retry_start"' "$T/e.jsonl")" = 2 ] || fail "exhaust: start count: $(grep auto_retry "$T/e.jsonl")"
grep -q '"type":"auto_retry_end","success":false,"attempt":3,"finalError":"stream failed:' "$T/e.jsonl" ||
    fail "exhaust: bad auto_retry_end: $(grep auto_retry "$T/e.jsonl")"
tail -1 "$T/e.jsonl" | grep -q '"status":"failed"' || fail "exhaust: not failed: $(tail -1 "$T/e.jsonl")"
printf '{"type":"error","error":{"type":"invalid_request_error","message":"bad request"}}' > "$T/bad.json"
serve "status:400:$T/bad.json"
pic submit e2 'fatal' > /dev/null
if pic --json run --model anthropic/m --api-url "$URL" > "$T/f.jsonl" 2> "$T/err"; then
    fail "fatal: succeeded unexpectedly"
fi
grep -q '"type":"auto_retry_' "$T/f.jsonl" && fail "fatal: emitted auto_retry without retry: $(grep auto_retry "$T/f.jsonl")"
printf 'PASS: exhausted retries emit auto_retry_end(success:false); non-retryable errors emit none\n'

# Compaction retry emits summarization_retry_scheduled -> attempt_start -> finished (not auto_retry_*).
serve "sse:$S/text.sse" "cut:$S/text.sse:420" "sse:$S/text.sse" "sse:$S/text.sse"
pic settings compaction '{"keepRecentTokens":1}' > /dev/null
pic submit m1 'first message for compaction' > /dev/null
pic --json run --model anthropic/m --api-url "$URL" > "$T/m1.jsonl" 2> "$T/err" || fail "compact seed: $(cat "$T/err")"
sid=$(pic sessions | awk 'NR==1{print $1}')
pic compact "$sid" > /dev/null
pic submit m2 'second message triggers compaction' --session "$sid" > /dev/null
pic --json run --model anthropic/m --api-url "$URL" > "$T/m2.jsonl" 2> "$T/err" || fail "compact retry: $(cat "$T/err")"
"$PIC" settings --unset compaction
grep -q '"type":"auto_retry_' "$T/m2.jsonl" && fail "compact retry: leaked auto_retry: $(grep retry "$T/m2.jsonl")"
cs=$(grep -n '"type":"compaction_start","reason":"manual"' "$T/m2.jsonl" | head -1 | cut -d: -f1)
sr=$(grep -n '"type":"summarization_retry_scheduled","attempt":2,"maxAttempts":3,"delayMs":0,"errorMessage":"stream failed:' "$T/m2.jsonl" | head -1 | cut -d: -f1)
sa=$(grep -n '{"type":"summarization_retry_attempt_start","source":"compaction","reason":"manual"}' "$T/m2.jsonl" | head -1 | cut -d: -f1)
sf=$(grep -n '{"type":"summarization_retry_finished"}' "$T/m2.jsonl" | head -1 | cut -d: -f1)
ce=$(grep -n '"type":"compaction_end","reason":"manual","result":' "$T/m2.jsonl" | head -1 | cut -d: -f1)
ea=$(grep -n '"type":"entry_appended","entry":{"type":"compaction"' "$T/m2.jsonl" | head -1 | cut -d: -f1)
[ -n "$cs" ] && [ -n "$sr" ] && [ -n "$sa" ] && [ -n "$sf" ] && [ -n "$ce" ] && [ -n "$ea" ] &&
    [ "$cs" -lt "$sr" ] && [ "$sr" -lt "$sa" ] && [ "$sa" -lt "$sf" ] && [ "$sf" -lt "$ce" ] && [ "$ce" -lt "$ea" ] ||
    fail "compact retry: order cs=$cs sr=$sr sa=$sa sf=$sf ce=$ce ea=$ea: $(types "$T/m2.jsonl")"
printf 'PASS: compaction retry emits summarization_retry_scheduled, attempt_start, finished, then compaction_end and entry_appended\n'

# Interrupt during compaction retry closes summarization_retry_finished and compaction_end before agent_end.
serve "sse:$S/text.sse" "retry:503:3" "retry:503:3" "retry:503:3" "retry:503:3"
pic settings compaction '{"keepRecentTokens":1}' > /dev/null
pic submit ci1 'seed for interrupted compaction' > /dev/null
pic --json run --model anthropic/m --api-url "$URL" > "$T/ci1.jsonl" 2> "$T/err" || fail "ci seed: $(cat "$T/err")"
sid=$(pic sessions | awk 'NR==1{print $1}')
pic compact "$sid" > /dev/null
pic submit ci2 'second message triggers compaction wait' --session "$sid" > /dev/null
perl -e '$SIG{INT} = "DEFAULT"; exec @ARGV' "$PIC" --db "$DB" --workspace "$WS" --json run --model anthropic/m --api-url "$URL" > "$T/ci2.jsonl" 2> "$T/err" &
rpid=$!
i=0
until grep -q '"type":"summarization_retry_scheduled"' "$T/ci2.jsonl"; do
    i=$((i + 1))
    [ "$i" -lt 200 ] || fail "ci: no summarization_retry_scheduled"
    sleep 0.05
done
kill -INT "$rpid"
wait "$rpid" || :
"$PIC" settings --unset compaction
cs=$(grep -n '"type":"compaction_start"' "$T/ci2.jsonl" | head -1 | cut -d: -f1)
sr=$(grep -n '"type":"summarization_retry_scheduled"' "$T/ci2.jsonl" | head -1 | cut -d: -f1)
sf=$(grep -n '{"type":"summarization_retry_finished"}' "$T/ci2.jsonl" | head -1 | cut -d: -f1)
ce=$(grep -n '"type":"compaction_end"' "$T/ci2.jsonl" | head -1 | cut -d: -f1)
ae=$(grep -n '"type":"agent_end"' "$T/ci2.jsonl" | head -1 | cut -d: -f1)
[ -n "$cs" ] && [ -n "$sr" ] && [ -n "$sf" ] && [ -n "$ce" ] && [ -n "$ae" ] &&
    [ "$cs" -lt "$sr" ] && [ "$sr" -lt "$sf" ] && [ "$sf" -lt "$ce" ] && [ "$ce" -lt "$ae" ] ||
    fail "ci: order cs=$cs sr=$sr sf=$sf ce=$ce ae=$ae: $(types "$T/ci2.jsonl")"
printf 'PASS: interrupting a compaction retry closes summarization_retry_finished and compaction_end before agent_end\n'

# entry_appended finds a submission's entry even when newer entries (such as bash) sit at head_seq.
serve "sse:$S/text.sse"
pic submit b1 'before bash' > /dev/null
sid=$(pic sessions | awk 'NR==1{print $1}')
sqlite3 "$DB" "
INSERT INTO pic_submission(request_key,content,status,session_id) VALUES('bash-a','echo a','answered','$sid');
INSERT INTO pic_entry(submission_id,kind,body) VALUES(last_insert_rowid(),'user','echo a');
INSERT INTO pic_bash(entry_seq,command,output,exit_code,cancelled,truncated,exclude) VALUES(last_insert_rowid(),'echo a','a',0,0,0,0);
INSERT INTO pic_submission(request_key,content,status,session_id) VALUES('bash-b','echo b','answered','$sid');
INSERT INTO pic_entry(submission_id,kind,body) VALUES(last_insert_rowid(),'user','echo b');
INSERT INTO pic_bash(entry_seq,command,output,exit_code,cancelled,truncated,exclude) VALUES(last_insert_rowid(),'echo b','b',0,0,0,0);
"
pic --json run --model anthropic/m --api-url "$URL" > "$T/b1.jsonl" 2> "$T/err" || fail "bash ahead: $(cat "$T/err")"
grep -q '"type":"entry_appended","entry":{"type":"message","id":"1",' "$T/b1.jsonl" ||
    fail "bash ahead: missed submission entry 1: $(grep entry_appended "$T/b1.jsonl")"
grep -q '"type":"entry_appended","entry":{"type":"message","id":"4",' "$T/b1.jsonl" ||
    fail "bash ahead: missed reply entry 4: $(grep entry_appended "$T/b1.jsonl")"
printf 'PASS: entry_appended emits a submission entry even when newer bash entries sit at head_seq\n'

# A running command reports its output so far.
serve "sse:$S/bash_out.sse" "sse:$S/text.sse"
pic submit u1 'run it' > /dev/null
pic --json run --model anthropic/m --api-url "$URL" > "$T/u.jsonl" 2> "$T/err" || fail "update: $(cat "$T/err")"
grep -q '"type":"tool_execution_update","toolCallId":"toolu_out","toolName":"bash","args":{[^}]*},"partialResult":{"content":\[{"type":"text","text":""}\],"details":{}}}' "$T/u.jsonl" ||
    fail "update: no initial update: $(types "$T/u.jsonl")"
grep -qF '"text":"first"}' "$T/u.jsonl" || fail "update: no partial: $(grep tool_execution "$T/u.jsonl")"
[ "$(types "$T/u.jsonl" | grep -o 'tool_execution_update' | head -1)" = tool_execution_update ] || fail "update: order"
u=$(grep -n tool_execution_update "$T/u.jsonl" | tail -1 | cut -d: -f1)
e=$(grep -n tool_execution_end "$T/u.jsonl" | cut -d: -f1)
[ "$u" -lt "$e" ] || fail "update: after end"
printf 'PASS: a running bash command emits tool_execution_update with its output so far\n'
