#!/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}
FAULTS=yes # --no-faults: skip cases that need crash hooks (the release build has none)
[ "${1:-}" = --no-faults ] && FAULTS=no
STREAMS=$(cd "$(dirname "$0")/streams" && pwd)
CHAT=$(cd "$(dirname "$0")/chat-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; }
# Runs pic with a crash hook and requires the hook's own exit status (77), so
# an unrelated failure cannot pass for the crash.
expect_crash() {
    point=$1
    shift
    rc=0
    env PIC_CRASH_AT="$point" "$PIC" --db "$DB" --workspace "$WS" "$@" 2>/dev/null || rc=$?
    [ "$rc" = 77 ] || fail "expected a crash at $point, got exit $rc"
}

SENTINEL="pic-sentinel-key-$$-7f3a9c"
export ANTHROPIC_API_KEY="$SENTINEL" OPENROUTER_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 anthropic/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":"bash"' "$req" || fail "text: tools"
pic dump | grep -q '^generation 1 1.0.1 done stop=stop' || fail "text: generation"
printf 'PASS: text answer and request shape\n'

# Project instructions from the workspace and its ancestors reach the system
# prompt, outermost first, with the working directory.
case_ instructions "sse:$STREAMS/text.sse"
mkdir "$WS/inner"
printf 'outer rule\n' > "$WS/AGENTS.md"
printf 'inner rule\n' > "$WS/inner/CLAUDE.md"
"$PIC" --db "$DB" --workspace "$WS/inner" run --provider anthropic --model anthropic/test-model --api-url "$URL" 2>> "$T/stderr" ||
    fail "instructions: run failed"
grep -q 'AGENTS.md\\">\\nouter rule\\n\\n</project_instructions>\\n\\n<project_instructions path=\\"[^"]*/inner/CLAUDE.md\\">\\ninner rule' "$LOG/1.req" ||
    fail "instructions: not in the system prompt in order"
grep -q '<cwd>\\n[^"]*/inner\\n</cwd>' "$LOG/1.req" || fail "instructions: cwd"
printf 'PASS: project instructions and cwd in the system prompt\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","content":"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":"Successfully wrote to notes.txt","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'

# Switching models mid-conversation (Pi's cross-provider rules). Turn 1 comes
# from model-a with thinking and a tool call whose id Anthropic would refuse;
# pic stops after the call's result (a crash hook, so dev builds only).
# Turn 2 to the same model replays turn 1 verbatim, thinking and all; turn 2
# to model-b gets it rebuilt from the neutral form: no thinking, and the id
# normalised the same way in the call and in its result.
if [ "$FAULTS" = yes ]; then
    for target in model-a model-b; do
        case_ "switch-$target" "sse:$STREAMS/thinking_tool.sse" "sse:$STREAMS/text.sse"
        expect_crash after-result:1 run --model anthropic/model-a --api-url "$URL"
        "$PIC" --db "$DB" --workspace "$WS" run --model "anthropic/$target" --api-url "$URL" 2>> "$T/stderr" ||
            fail "switch to $target: run failed"
        [ "$(status)" = answered ] || fail "switch to $target: $(status)"
        if [ "$target" = model-a ]; then
            grep -q '{"role":"assistant","content":\[{"type":"thinking","thinking":"Write it.","signature":"SIG-A-123"},{"type":"tool_use","id":"call|item.1"' "$LOG/2.req" ||
                fail "switch: same model did not get the turn verbatim"
            grep -q '"tool_use_id":"call|item.1"' "$LOG/2.req" || fail "switch: same model result id"
        else
            if grep -q '"type":"thinking"' "$LOG/2.req"; then fail "switch: another model got the thinking"; fi
            grep -q '{"role":"assistant","content":\[{"type":"tool_use","id":"call_item_1","name":"write","input":{"path":"t.txt","content":"x"}}\]}' "$LOG/2.req" ||
                fail "switch: call not rebuilt with a normalised id"
            grep -q '"tool_use_id":"call_item_1"' "$LOG/2.req" || fail "switch: result id not normalised to match"
        fi
        pic dump | grep -q "^entry 2 1 assistant | .*\"toolCall\",\"id\":\"call|item.1\"" || fail "switch: neutral form"
        pic check > /dev/null || fail "switch: integrity"
    done
    printf 'PASS: a turn goes verbatim to its own model and converted to another\n'
fi

# 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 '{"type":"thinking","thinking":"Two plus two.","signature":"EqQBCgIYAhIM1gbcDa9GJwZA2b3h"},{"type":"thinking","thinking":"","signature":"EmwKAhgBEgy3va3pzix/LafPsn4a","redacted":true}' || fail "thinking: neutral form"
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":"write needs string inputs path and content","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 anthropic/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"
# env, not a prefix on the pic function: POSIX sh lets such an assignment persist.
if env ANTHROPIC_API_KEY= "$PIC" --db "$DB" --workspace "$WS" run --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'

# ---- Chat Completions (OpenRouter, OpenAI, compatible servers)
chat() { pic run --model openrouter/test/model --api-url "$URL" 2>> "$T/stderr"; }

case_ chat-text "sse:$CHAT/text.sse"
chat > "$T/out" || fail "chat text: run failed"
[ "$(status)" = answered ] || fail "chat text: $(status)"
pic dump | grep -q 'answer | \[{"type":"text","text":"Hello, \\"world\\"\\n"}\]$' || fail "chat text: answer"
req="$LOG/1.req"
grep -q "^Authorization: Bearer $SENTINEL" "$req" || fail "chat text: key not sent as a bearer token"
grep -q '"model":"test/model"' "$req" || fail "chat text: model"
grep -q '"messages":\[{"role":"system","content":"You are a coding assistant' "$req" || fail "chat text: system message"
grep -q '{"role":"user","content":"make notes"}' "$req" || fail "chat text: user message"
grep -q '"tools":\[{"type":"function","function":{"name":"read"' "$req" || fail "chat text: tools"
grep -q '"stream_options":{"include_usage":true}' "$req" || fail "chat text: usage requested"
pic dump | grep -q '^generation 1 1.0.1 done stop=stop' || fail "chat text: generation"
printf 'PASS: chat: text answer and request shape\n'

case_ chat-tools "sse:$CHAT/tools.sse" "sse:$CHAT/text.sse"
chat || fail "chat tools: run failed"
[ "$(cat "$WS/notes.txt")" = hi ] || fail "chat tools: first call did not run"
grep -q '{"role":"assistant","content":null,"tool_calls":\[{"id":"call_a","type":"function","function":{"name":"write","arguments":"{\\"path\\":\\"notes.txt\\",\\"content\\":\\"hi\\"}"}},{"id":"call_b"' "$LOG/2.req" ||
    fail "chat tools: turn not replayed verbatim"
grep -q '{"role":"tool","tool_call_id":"call_a","content":"Successfully wrote to notes.txt"},{"role":"tool","tool_call_id":"call_b","content":"' "$LOG/2.req" ||
    fail "chat tools: results not sent as tool messages in order"
printf 'PASS: chat: parallel calls run and go back as tool messages\n'

case_ chat-reasoning "sse:$CHAT/reasoning_tool.sse" "sse:$CHAT/text.sse"
chat || fail "chat reasoning: run failed"
grep -q '"tool_calls":\[{"id":"call_r".*\],"reasoning_content":"Check it."}' "$LOG/2.req" ||
    fail "chat reasoning: reasoning not replayed under its own field"
printf 'PASS: chat: reasoning goes back under the field it came in\n'

case_ chat-nofinish "sse:$CHAT/no_finish.sse" "sse:$CHAT/text.sse"
chat || fail "chat no finish: run failed"
[ "$(status) $(failed_generations)" = "answered 1" ] || fail "chat no finish: $(status) $(failed_generations)"
case_ chat-error "sse:$CHAT/error.sse" "sse:$CHAT/text.sse"
chat || fail "chat error: run failed"
[ "$(status) $(failed_generations)" = "answered 1" ] || fail "chat error: $(status) $(failed_generations)"
pic dump | grep -q '^generation 1 1.0.1 failed | stream failed: Upstream overloaded$' || fail "chat error: message"
case_ chat-filter "sse:$CHAT/content_filter.sse"
if chat; then fail "chat filter: succeeded"; fi
[ "$(status)" = failed ] || fail "chat filter: $(status)"
printf 'PASS: chat: broken streams retried, a content filter fails the submission\n'

# Across providers, both ways: an Anthropic turn continued by a Chat model,
# and a Chat turn continued by an Anthropic model.
if [ "$FAULTS" = yes ]; then
    case_ cross-a2c "sse:$STREAMS/thinking_tool.sse" "sse:$CHAT/text.sse"
    expect_crash after-result:1 run --model anthropic/model-a --api-url "$URL"
    chat || fail "a2c: run failed"
    [ "$(status)" = answered ] || { pic dump >&2; ls "$LOG" >&2; fail "a2c: $(status)"; }
    if grep -qi 'thinking\|SIG-A' "$LOG/2.req"; then fail "a2c: Anthropic thinking sent to a Chat model"; fi
    grep -q '{"role":"assistant","content":null,"tool_calls":\[{"id":"call_item_1","type":"function","function":{"name":"write","arguments":"{\\"path\\":\\"t.txt\\",\\"content\\":\\"x\\"}"}}\]}' "$LOG/2.req" ||
        fail "a2c: call not rebuilt for Chat Completions"
    grep -q '{"role":"tool","tool_call_id":"call_item_1","content":"Successfully wrote to t.txt"}' "$LOG/2.req" ||
        fail "a2c: result id not normalised to match"

    case_ cross-c2a "sse:$CHAT/reasoning_tool.sse" "sse:$STREAMS/text.sse"
    expect_crash after-result:1 run --model openrouter/test/model --api-url "$URL"
    pic run --model anthropic/model-x --api-url "$URL" 2>> "$T/stderr" || fail "c2a: run failed"
    [ "$(status)" = answered ] || fail "c2a: $(status)"
    if grep -q 'reasoning_content\|Check it' "$LOG/2.req"; then fail "c2a: Chat reasoning sent to Anthropic"; fi
    grep -q '{"role":"assistant","content":\[{"type":"tool_use","id":"call_r","name":"bash","input":{"command":"true"}}\]}' "$LOG/2.req" ||
        fail "c2a: call not rebuilt for the Messages API"
    grep -q '"tool_use_id":"call_r"' "$LOG/2.req" || fail "c2a: result id"
    pic check > /dev/null || fail "cross: integrity"
    printf 'PASS: a conversation moves between Anthropic and Chat Completions both ways\n'
fi

# 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'
