#!/bin/sh
# Images, as Pi sends them: pic ask --image, the RPC images field of steer
# and follow_up, and the read tool on an image file, journaled in SQLite
# (deduplicated, compressed only when that is smaller) and sent in each API's
# own shape, or as Pi's placeholder to a model without image input. Exports
# carry them; a crash around the image write leaves a consistent journal.
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
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
C=$here/chat-streams
I=$here/image-streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-images.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME"
spid=
pid=
cleanup() {
    exec 3>&- 2>/dev/null || :
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    [ -n "$pid" ] && kill -9 "$pid" 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-images-test-key PIC_PI_EXPORT=0 PIC_MODEL_CATALOG=offline

# A 1x1 PNG, and its base64 as every API carries it.
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"
[ "$(wc -c < "$T/dot.png" | tr -d ' ')" = 70 ] || fail "fixture: dot.png"

n=0
serve() { # SPEC...: a fresh server, journal and workspace (with dot.png)
    [ -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"
    cp "$T/dot.png" "$WS/dot.png"
    "$SERVER" "$T/port$n" "$LOG" 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
    # One provider per API at the fake server; "see" takes images, "blind" does not (Pi's default).
    port=$(cat "$T/port$n")
    printf '{"providers":{%s,%s,%s}}' \
        "\"va\":{\"baseUrl\":\"http://127.0.0.1:$port\",\"api\":\"anthropic-messages\",\"apiKey\":\"\$ANTHROPIC_API_KEY\",\"models\":[{\"id\":\"see\",\"input\":[\"text\",\"image\"]},{\"id\":\"blind\"}]}" \
        "\"vc\":{\"baseUrl\":\"http://127.0.0.1:$port\",\"api\":\"openai-completions\",\"apiKey\":\"\$ANTHROPIC_API_KEY\",\"models\":[{\"id\":\"see\",\"input\":[\"text\",\"image\"]},{\"id\":\"blind\",\"input\":[\"text\"]}]}" \
        "\"vr\":{\"baseUrl\":\"http://127.0.0.1:$port\",\"api\":\"openai-responses\",\"apiKey\":\"\$ANTHROPIC_API_KEY\",\"models\":[{\"id\":\"see\",\"input\":[\"text\",\"image\"]},{\"id\":\"blind\"}]}" \
        > "$T/models$n.json"
    export PIC_MODELS_FILE="$T/models$n.json"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
has() { grep -qF -- "$2" "$1" || fail "$3: $(grep -o '"messages".*\|"input".*' "$1" | cut -c1-600)"; }
hasnt() { ! grep -qF -- "$2" "$1" || fail "$3"; }
ANT_IMG='{"type":"image","source":{"type":"base64","media_type":"image/png","data":"'$PNG_B64'"}}'
URL_IMG='{"type":"image_url","image_url":{"url":"data:image/png;base64,'$PNG_B64'"}}'
RESP_IMG='{"type":"input_image","detail":"auto","image_url":"data:image/png;base64,'$PNG_B64'"}'
USER_PH='(image omitted: model does not support images)'
TOOL_PH='(tool image omitted: model does not support images)'

# Anthropic, a model with image input: the text, then the image block.
serve "sse:$S/text.sse"
pic --model va/see ask --image "$T/dot.png" 'what is this' > /dev/null 2>> "$T/err" || fail "ask: $(cat "$T/err")"
has "$LOG/1.req" '"messages":[{"role":"user","content":[{"type":"text","text":"what is this"},'"$ANT_IMG"']}]' "anthropic: user image"
pic check > /dev/null || fail "anthropic: integrity"
pic dump | grep -q '^image 1 entry=1.0 image/png 70 [a-z]* | [0-9a-f]\{64\}$' || fail "anthropic: dump: $(pic dump | grep '^image')"
# The same bytes again are stored once; a highly compressible one is
# deflated, noise (as most image data is) kept raw.
{ printf 'GIF89a'; head -c 20000 /dev/zero; } > "$T/flat.gif"
{ cat "$T/dot.png"; head -c 3000 /dev/urandom; } > "$T/noise.png"
pic --model va/see ask -c --image "$T/dot.png" --image "$T/flat.gif" --image "$T/noise.png" 'and these' > /dev/null 2>> "$T/err" || fail "ask 2: $(cat "$T/err")"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_image')" = 3 ] || fail "dedup: $(sqlite3 "$DB" 'SELECT hash, mime, sz FROM pic_image')"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_attachment')" = 4 ] || fail "dedup: attachments"
pic dump | grep -q '^image 3 entry=3.1 image/gif 20006 deflated | ' && pic dump | grep -q '^image 4 entry=3.2 image/png 3070 raw | ' ||
    fail "deflate: $(pic dump | grep '^image')"
GIF_B64=$(base64 < "$T/flat.gif" | tr -d '\n')
has "$LOG/2.req" '{"type":"text","text":"and these"},'"$ANT_IMG"',{"type":"image","source":{"type":"base64","media_type":"image/gif","data":"'"$GIF_B64"'"}},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"'"$(base64 < "$T/noise.png" | tr -d '\n')"'"}}]}]' \
    "anthropic: three images, the deflated one restored"
has "$LOG/2.req" '{"role":"user","content":[{"type":"text","text":"what is this"},'"$ANT_IMG"']}' "anthropic: history keeps its image"
pic check > /dev/null || fail "dedup: integrity"
# pic check holds attachments to their images and owners.
cp "$DB" "$T/broken.sqlite"
sqlite3 "$T/broken.sqlite" "DELETE FROM pic_image WHERE mime = 'image/gif'"
"$PIC" --db "$T/broken.sqlite" --workspace "$WS" check > /dev/null 2> "$T/check" && fail "check: a missing image passed"
grep -q 'integrity violation: attachment without its image' "$T/check" || fail "check: $(cat "$T/check")"
printf 'PASS: anthropic: ask --image sends Pi image blocks; images are stored once, deflated only when smaller\n'

# Pi session lines and the HTML page carry them.
pic export --pi - > "$T/pi.jsonl" || fail "export --pi"
grep -qF '"content":[{"type":"text","text":"what is this"},{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]' "$T/pi.jsonl" ||
    fail "export --pi: $(grep -o '"role":"user".\{0,200\}' "$T/pi.jsonl")"
pic export --html latest - > "$T/page.html" || fail "export --html"
grep -qF '<img src="data:image/png;base64,'"$PNG_B64"'" class="message-image" alt="">' "$T/page.html" || fail "export --html: no image"
printf 'PASS: export: Pi session lines and the HTML page carry the images\n'

# A model without image input gets Pi's placeholder, once for all its images.
serve "sse:$S/text.sse"
pic --model va/blind ask --image "$T/dot.png" --image "$T/dot.png" 'blind' > /dev/null 2>> "$T/err" || fail "blind: $(cat "$T/err")"
has "$LOG/1.req" '"messages":[{"role":"user","content":[{"type":"text","text":"blind"},{"type":"text","text":"'"$USER_PH"'"}]}]' "anthropic: placeholder"
hasnt "$LOG/1.req" "$PNG_B64" "anthropic: image sent to a model without image input"
printf 'PASS: anthropic: a model without image input gets Pi'"'"'s placeholder\n'

# Not an image: refused. A BMP (Pi converts it; pic cannot) and an oversized
# image become Pi's notes after the text, nothing attached.
serve "sse:$S/text.sse"
printf 'plain' > "$T/plain.txt"
if pic --model va/see ask --image "$T/plain.txt" 'x' > /dev/null 2> "$T/err1"; then fail "a text file was attached"; fi
grep -q 'is not an image' "$T/err1" || fail "not an image: $(cat "$T/err1")"
printf 'BM\0\0\0\0\0\0\0\0\066\0\0\0\050\0\0\0\001\0\0\0\001\0\0\0\001\0\030\0' > "$T/x.bmp"
{ cat "$T/dot.png"; head -c 3600000 /dev/zero; } > "$T/big.png"
pic --model va/see ask --image "$T/x.bmp" --image "$T/big.png" 'notes' > /dev/null 2>> "$T/err" || fail "notes: $(cat "$T/err")"
has "$LOG/1.req" '"content":"notes\n\n[Image omitted: could not be converted to a supported inline image format.]\n[Image omitted: could not be resized below the inline image size limit.]"' "notes"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_attachment')" = 0 ] || fail "notes: something attached"
printf 'PASS: ask --image refuses a non-image; BMP and oversized images become Pi'"'"'s notes\n'

# The read tool on an image file: Pi's note and the image in the tool result.
serve "sse:$I/read_png.sse" "sse:$S/text.sse"
pic --model va/see --json ask 'look at dot.png' > "$T/readev" 2>> "$T/err" || fail "read: $(cat "$T/err")"
grep -qF '{"type":"tool_execution_end","toolCallId":"toolu_r","toolName":"read","result":{"content":[{"type":"text","text":"Read image file [image/png]"},{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]},"isError":false}' "$T/readev" ||
    fail "read: tool_execution_end: $(grep tool_execution_end "$T/readev")"
has "$LOG/2.req" '{"type":"tool_result","tool_use_id":"toolu_r","content":[{"type":"text","text":"Read image file [image/png]"},'"$ANT_IMG"'],"is_error":false}' "anthropic: read result"
pic dump | grep -q '^image 1 entry=3.0 image/png 70 ' || fail "read: dump: $(pic dump)"
pic check > /dev/null || fail "read: integrity"
serve "sse:$I/read_png.sse" "sse:$S/text.sse"
pic --model va/blind ask 'look at dot.png' > /dev/null 2>> "$T/err" || fail "read blind: $(cat "$T/err")"
has "$LOG/2.req" '{"type":"tool_result","tool_use_id":"toolu_r","content":"Read image file [image/png]\n'"$TOOL_PH"'","is_error":false}' "anthropic: read result, placeholder"
printf 'PASS: anthropic: read on a PNG returns Pi'"'"'s note and the image, or the placeholder\n'

# Chat Completions: image_url parts; a tool's images follow the run of tool
# results in one user message.
serve "sse:$C/text.sse"
pic --model vc/see ask --image "$T/dot.png" 'chat image' > /dev/null 2>> "$T/err" || fail "chat: $(cat "$T/err")"
has "$LOG/1.req" '{"role":"user","content":[{"type":"text","text":"chat image"},'"$URL_IMG"']}' "chat: user image"
serve "sse:$I/chat_read_png.sse" "sse:$C/text.sse"
pic --model vc/see ask 'look' > /dev/null 2>> "$T/err" || fail "chat read: $(cat "$T/err")"
has "$LOG/2.req" '{"role":"tool","tool_call_id":"call_r","content":"Read image file [image/png]"},{"role":"user","content":[{"type":"text","text":"Attached image(s) from tool result:"},'"$URL_IMG"']}]' "chat: tool image"
serve "sse:$I/chat_read_png.sse" "sse:$C/text.sse"
pic --model vc/blind ask --image "$T/dot.png" 'look' > /dev/null 2>> "$T/err" || fail "chat blind: $(cat "$T/err")"
has "$LOG/2.req" '{"role":"user","content":[{"type":"text","text":"look"},{"type":"text","text":"'"$USER_PH"'"}]}' "chat: placeholder"
has "$LOG/2.req" '{"role":"tool","tool_call_id":"call_r","content":"Read image file [image/png]\n'"$TOOL_PH"'"}]' "chat: tool placeholder"
hasnt "$LOG/2.req" "$PNG_B64" "chat: image sent to a model without image input"
printf 'PASS: chat: image_url parts, tool images after the results, placeholders without image input\n'

# Responses: input_image items; a tool's images in its output.
serve "sse:$I/responses_read_png.sse" "sse:$here/responses-streams/reasoning_text.sse"
pic --model vr/see ask --image "$T/dot.png" 'resp' > /dev/null 2>> "$T/err" || fail "responses: $(cat "$T/err")"
has "$LOG/1.req" '{"role":"user","content":[{"type":"input_text","text":"resp"},'"$RESP_IMG"']}' "responses: user image"
has "$LOG/2.req" '{"type":"function_call_output","call_id":"call_r","output":[{"type":"input_text","text":"Read image file [image/png]"},'"$RESP_IMG"']}' "responses: tool image"
serve "sse:$I/responses_read_png.sse" "sse:$here/responses-streams/reasoning_text.sse"
pic --model vr/blind ask --image "$T/dot.png" 'resp' > /dev/null 2>> "$T/err" || fail "responses blind: $(cat "$T/err")"
has "$LOG/2.req" '{"role":"user","content":[{"type":"input_text","text":"resp"},{"type":"input_text","text":"'"$USER_PH"'"}]}' "responses: placeholder"
has "$LOG/2.req" '{"type":"function_call_output","call_id":"call_r","output":"Read image file [image/png]\n'"$TOOL_PH"'"}' "responses: tool placeholder"
hasnt "$LOG/2.req" "$PNG_B64" "responses: image sent to a model without image input"
printf 'PASS: responses: input_image items in messages and tool output, placeholders without image input\n'

# RPC: images on steer and follow_up are journaled with the message and
# delivered with it; a malformed one is an error response.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
rm -f "$T/in"
mkfifo "$T/in"
"$PIC" --db "$DB" --workspace "$WS" --model va/see --json --commands ask 'hold on' < "$T/in" > "$T/ev" 2> "$T/everr" &
pid=$!
exec 3> "$T/in"
i=0
until [ -e "$WS/started" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "rpc: never started: $(cat "$T/everr")"; sleep 0.05; done
printf '%s\n' '{"id":"s","type":"steer","message":"see this","images":[{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]}' >&3
printf '%s\n' '{"id":"f","type":"follow_up","message":"and this","images":[{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/svg+xml"}]}' >&3
printf '%s\n' '{"id":"b1","type":"steer","message":"x","images":"nope"}' >&3
printf '%s\n' '{"id":"b2","type":"steer","message":"x","images":[{"type":"image","data":"%%%","mimeType":"image/png"}]}' >&3
printf '%s\n' '{"id":"b3","type":"follow_up","message":"x","images":[{"data":"aGk="}]}' >&3
i=0
until grep -qF '"id":"b3"' "$T/ev"; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "rpc: responses: $(cat "$T/ev")"; sleep 0.05; done
touch "$WS/release"
rc=0
wait "$pid" || rc=$?
pid=
exec 3>&-
[ "$rc" = 0 ] || fail "rpc: exit $rc: $(cat "$T/everr")"
grep -qF '{"id":"s","type":"response","command":"steer","success":true,"data":{"disposition":"queued"}}' "$T/ev" || fail "rpc: steer response"
grep -qF '{"id":"b1","type":"response","command":"steer","success":false,"error":"images must be an array"}' "$T/ev" || fail "rpc: b1"
grep -qF '{"id":"b2","type":"response","command":"steer","success":false,"error":"image data is not base64"}' "$T/ev" || fail "rpc: b2"
grep -qF '"id":"b3","type":"response","command":"follow_up","success":false,"error":"each image must be' "$T/ev" || fail "rpc: b3"
has "$LOG/2.req" '{"role":"user","content":[{"type":"text","text":"see this"},'"$ANT_IMG"']}' "rpc: steer image"
grep -qF '{"type":"message_start","message":{"role":"user","content":[{"type":"text","text":"see this"},{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]}}' "$T/ev" ||
    fail "rpc: message_start without the image"
# An SVG cannot go inline (Pi would convert it): the follow-up runs with Pi's note instead.
has "$LOG/3.req" '{"role":"user","content":"and this\n\n[Image omitted: could not be converted to a supported inline image format.]"}' "rpc: follow-up note"
pic check > /dev/null || fail "rpc: integrity"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_attachment WHERE queued_id IS NOT NULL")" = 1 ] || fail "rpc: queued attachment"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_attachment WHERE entry_seq IS NOT NULL")" = 1 ] || fail "rpc: delivered attachment"
printf 'PASS: rpc: images on steer and follow_up are journaled and delivered; malformed ones are refused\n'

[ "$FAULTS" = yes ] || exit 0
# A crash while the image is written leaves nothing of the request; a crash
# after a read's result keeps the result and its image together.
serve "sse:$S/text.sse"
rc=0
env PIC_CRASH_AT=after-image:1 "$PIC" --db "$DB" --workspace "$WS" --model va/see ask --image "$T/dot.png" 'crash' > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "crash: expected 77, got $rc"
pic check > /dev/null || fail "crash: integrity after the image write"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_submission') $(sqlite3 "$DB" 'SELECT count(*) FROM pic_image')" = "0 0" ] ||
    fail "crash: a partial request survived"
for point in after-image:1 after-result:1; do
    serve "sse:$I/read_png.sse" "sse:$S/text.sse"
    rc=0
    env PIC_CRASH_AT=$point "$PIC" --db "$DB" --workspace "$WS" --model va/see ask 'look again' > /dev/null 2>&1 || rc=$?
    [ "$rc" = 77 ] || fail "crash at $point: expected 77, got $rc"
    pic check > /dev/null || fail "crash at $point: integrity"
    got="$(sqlite3 "$DB" "SELECT count(*) FROM pic_entry WHERE kind = 'tool_result'") $(sqlite3 "$DB" "SELECT count(*) FROM pic_attachment")"
    case $point in
    after-image:1) [ "$got" = "0 0" ] || fail "crash at $point: results and images: $got" ;;
    after-result:1) [ "$got" = "1 1" ] || fail "crash at $point: results and images: $got" ;;
    esac
    # The next pic finishes the request: a lost read runs again.
    pic --model va/see run > /dev/null 2>> "$T/err" || fail "crash at $point: recovery: $(cat "$T/err")"
    pic check > /dev/null || fail "crash at $point: integrity after recovery"
    got="$(sqlite3 "$DB" "SELECT count(*) FROM pic_entry WHERE kind = 'tool_result'") $(sqlite3 "$DB" "SELECT count(*) FROM pic_attachment") $(sqlite3 "$DB" "SELECT status FROM pic_submission")"
    [ "$got" = "1 1 answered" ] || fail "crash at $point: after recovery: $got"
    has "$LOG/2.req" "$ANT_IMG" "crash at $point: the image did not reach the model"
done
printf 'PASS: crashes around the image write leave the request and its images whole\n'
