#!/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 100 ] || 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 turn_start message_start message_update message_end tool_execution_start tool_execution_end turn_end turn_start message_start message_update message_update message_end turn_end agent_end "
[ "$(types "$T/a.jsonl")" = "$want" ] || fail "json: event order: $(types "$T/a.jsonl")"
# Each line is JSON (checked with the sqlite3 command where there is one).
if command -v sqlite3 > /dev/null; then
    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"
fi
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, 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"
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 and is retried\n'

# A transport retry reports the real wait before it.
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")"
printf 'PASS: auto_retry_start carries the backoff it is about to wait\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'
