#!/bin/sh
# The Messages API provider end to end against a local fake server: request
# shape, replay of content, retries, failures, a cut stream, a crash
# mid-stream, and that the API key never reaches pic's database or output.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
STREAMS=$(cd "$(dirname "$0")/streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-provider.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; }

SENTINEL="pic-sentinel-key-$$-7f3a9c"
export ANTHROPIC_API_KEY="$SENTINEL"

serve() { # serve NAME SPEC...: start a fake server for the next case
    [ -n "$spid" ] && kill "$spid" 2>/dev/null && wait "$spid" 2>/dev/null || true
    LOG="$T/$1-log"
    mkdir "$LOG"
    rm -f "$T/port"
    shift
    "$SERVER" "$T/port" "$LOG" 60 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port" ]; 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")/v1/messages"
}
fresh() { DB="$T/$1.sqlite"; WS="$T/$1-ws"; mkdir "$WS"; }
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
run() { pic run --provider anthropic --model test-model --api-url "$URL" 2>> "$T/stderr"; }
case_() { # case_ NAME SPEC...: fresh journal, fake server, one submission
    fresh "$1"
    serve "$@"
    pic submit job-1 'make notes' > /dev/null
}
status() { pic dump | sed -n 's/^submission 1 job-1 \([a-z]*\) .*/\1/p'; }
failed_generations() { pic dump | grep -c '^generation .* failed' || true; }
requests() { ls "$LOG" | wc -l | tr -d ' '; }

# A text answer, and the request that asked for it.
case_ text "sse:$STREAMS/text.sse"
run > "$T/out" || fail "text: run failed"
[ "$(status)" = answered ] || fail "text: $(status)"
pic dump | grep -q 'answer | \[{"type":"text","text":"Hello, \\"world\\"\\n"}\]$' || fail "text: answer not verbatim"
req="$LOG/1.req"
grep -q '^POST /v1/messages HTTP/1.1' "$req" || fail "text: request line"
grep -q '^anthropic-version: 2026-10-21' "$req" || fail "text: version header"
grep -q "^x-api-key: $SENTINEL" "$req" || fail "text: key not sent"
grep -q '"model":"test-model"' "$req" || fail "text: model"
grep -q '"stream":true' "$req" || fail "text: stream"
grep -q '"messages":\[{"role":"user","content":"make notes"}\]' "$req" || fail "text: messages"
grep -q '"name":"write"' "$req" && grep -q '"name":"exec"' "$req" || fail "text: tools"
pic dump | grep -q '^generation 1 1.0.1 done stop=end_turn' || fail "text: generation"
printf 'PASS: text answer and request shape\n'

# A tool turn: the call runs, then the next request replays the assistant
# content verbatim and returns the result under its call id.
case_ tool "sse:$STREAMS/tool_use.sse" "sse:$STREAMS/text.sse"
run || fail "tool: run failed"
[ "$(cat "$WS/notes.txt")" = hi ] || fail "tool: file not written"
grep -q '{"role":"assistant","content":\[{"type":"text","text":"Writing it."},{"type":"tool_use","id":"toolu_01","name":"write","input":{"path":"notes.txt","text":"hi"}}\]}' "$LOG/2.req" ||
    fail "tool: assistant content not replayed verbatim"
grep -q '{"role":"user","content":\[{"type":"tool_result","tool_use_id":"toolu_01","content":"wrote notes.txt (3 bytes)","is_error":false}\]}' "$LOG/2.req" ||
    fail "tool: tool result not sent"
printf 'PASS: tool call runs and its result is sent back under its id\n'

# Two calls in one turn go back as one user message with two results.
case_ parallel "sse:$STREAMS/parallel_tools.sse" "sse:$STREAMS/text.sse"
run || fail "parallel: run failed"
grep -q '"tool_use_id":"toolu_a".*},{"type":"tool_result","tool_use_id":"toolu_b"' "$LOG/2.req" ||
    fail "parallel: results not grouped in call order"
printf 'PASS: parallel calls answered in one message, in order\n'

# Thinking blocks and their signatures go back byte for byte.
case_ thinking "sse:$STREAMS/thinking.sse"
run || fail "thinking: run failed"
pic dump | grep -q '"signature":"EqQBCgIYAhIM1gbcDa9GJwZA2b3h"},{"type":"redacted_thinking"' || fail "thinking: blocks"
printf 'PASS: thinking blocks journaled verbatim\n'

# 429 and 503 are retried within the generation, honouring Retry-After.
case_ retry status:429:- status:503:- "sse:$STREAMS/text.sse"
run || fail "retry: run failed"
[ "$(status) $(failed_generations) $(requests)" = "answered 0 3" ] || fail "retry: $(status) $(failed_generations) $(requests)"
printf 'PASS: 429 and 5xx retried before the stream\n'

# Persistent 5xx: four tries per generation, three generations, then failed.
case_ exhausted status:500:-
if run; then fail "exhausted: succeeded"; fi
[ "$(status) $(failed_generations) $(requests)" = "failed 3 12" ] || fail "exhausted: $(status) $(failed_generations) $(requests)"
printf 'PASS: server errors retried, then the submission fails\n'

# 401 is not retried, and the API's message is kept.
printf '{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}' > "$T/401.json"
case_ unauthorized "status:401:$T/401.json"
if run; then fail "401: succeeded"; fi
[ "$(status) $(failed_generations) $(requests)" = "failed 1 1" ] || fail "401: $(status) $(failed_generations) $(requests)"
pic dump | grep -q 'error=HTTP 401: invalid x-api-key$' || fail "401: message lost"
printf 'PASS: 401 fails at once with the API message\n'

# A stream cut mid-way fails that generation; the turn is asked again and no
# tool call from the partial message runs.
case_ cut "cut:$STREAMS/tool_use.sse:700" "sse:$STREAMS/text.sse"
run || fail "cut: run failed"
[ "$(status) $(failed_generations) $(requests)" = "answered 1 2" ] || fail "cut: $(status) $(failed_generations) $(requests)"
[ ! -e "$WS/notes.txt" ] || fail "cut: a tool from the partial stream ran"
pic dump | grep -q '^generation 1 1.0.1 failed | stream failed' || fail "cut: error not recorded"
printf 'PASS: a cut stream is retried as a new attempt\n'

# A malformed stream is a failed attempt too.
case_ malformed "sse:$STREAMS/malformed.sse" "sse:$STREAMS/text.sse"
run || fail "malformed: run failed"
[ "$(status) $(failed_generations)" = "answered 1" ] || fail "malformed: $(status) $(failed_generations)"
printf 'PASS: a malformed stream is retried\n'

# A refusal fails the submission without running anything.
case_ refusal "sse:$STREAMS/refusal.sse"
if run; then fail "refusal: succeeded"; fi
[ "$(status)" = failed ] || fail "refusal: $(status)"
printf 'PASS: a refusal fails the submission\n'

# Tool input cut by max_tokens reaches the tool as bad input and is reported.
case_ max_tokens "sse:$STREAMS/max_tokens.sse" "sse:$STREAMS/text.sse"
run || fail "max_tokens: run failed"
grep -q '"content":"error: write needs string inputs path and text","is_error":true' "$LOG/2.req" ||
    fail "max_tokens: bad input not reported to the model"
printf 'PASS: truncated tool input is rejected by the tool, not run\n'

# pic killed while the stream is in flight: the attempt is failed on restart
# and the turn is asked again.
case_ midstream "hang:$STREAMS/tool_use.sse:400" "sse:$STREAMS/text.sse"
"$PIC" --db "$DB" --workspace "$WS" run --provider anthropic --model test-model --api-url "$URL" 2>/dev/null &
victim=$!
i=0
while [ ! -s "$LOG/1.req" ]; do
    i=$((i + 1))
    [ "$i" -lt 100 ] || fail "midstream: request never arrived"
    sleep 0.05
done
sleep 0.5
kill -9 "$victim"
wait "$victim" 2>/dev/null || true
run || fail "midstream: restart failed"
[ "$(status) $(failed_generations)" = "answered 1" ] || fail "midstream: $(status) $(failed_generations)"
pic dump | grep -q '^generation 1 1.0.1 failed | interrupted before the reply was recorded$' ||
    fail "midstream: attempt not marked interrupted"
pic check > /dev/null || fail "midstream: integrity"
printf 'PASS: a crash mid-stream is recovered as a failed attempt\n'

# Without a key nothing is sent and the error says what to set.
case_ nokey "sse:$STREAMS/text.sse"
if ANTHROPIC_API_KEY= pic run --provider anthropic --api-url "$URL" 2> "$T/nokey.err"; then fail "nokey: succeeded"; fi
grep -q 'ANTHROPIC_API_KEY is not set' "$T/nokey.err" || fail "nokey: $(cat "$T/nokey.err")"
[ "$(requests)" = 0 ] || fail "nokey: a request was sent"
printf 'PASS: a missing key sends nothing\n'

# The key went to the server and nowhere else: not the database, its WAL, or
# anything pic printed.
kill "$spid" 2>/dev/null || true
wait "$spid" 2>/dev/null || true
spid=
grep -rl "$SENTINEL" "$T"/*-log > /dev/null || fail "leak: sentinel never sent (test is broken)"
for f in "$T"/*.sqlite* "$T/stderr" "$T/out" "$T"/*.err; do
    [ -e "$f" ] || continue
    if grep -q "$SENTINEL" "$f"; then fail "leak: key found in $f"; fi
done
printf 'PASS: the API key never reaches the journal or output\n'
