#!/bin/sh
# pic import --claude: a Claude Code transcript as a new conversation, its
# main thread only (sidechains, meta, synthetic and abandoned branches left
# out), from its latest compact summary, cut before --until; tool calls
# journaled as pic's tools, already done, and the rest rendered as text; the
# result passes pic check and continues at each API with every tool call
# paired with its result. The fixtures are synthetic.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
here=$(cd "$(dirname "$0")" && pwd)
F=$here/claude-transcripts
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-import-claude.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=k OPENROUTER_API_KEY=k OPENAI_API_KEY=k PIC_PI_EXPORT=0 PIC_MODEL_CATALOG=offline
"$PIC" settings cacheRetention none > /dev/null

WS="$T/ws"
mkdir "$WS"
sed "s|@WS@|$WS|g" "$F/basic.jsonl" > "$T/basic.jsonl"
sed "s|@WS@|$WS|g" "$F/compact.jsonl" > "$T/compact.jsonl"
DB="$T/j.sqlite"
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
q() { sqlite3 "$DB" "$1"; }
# import FILE [ARGS]: the new id; stdout kept in $T/out
import() {
    f=$1
    shift
    pic import --claude "$f" "$@" > "$T/out" 2> "$T/err" || fail "import $*: $(cat "$T/err")"
    [ ! -s "$T/err" ] || fail "import $*: wrote to stderr"
    pic check > /dev/null || fail "import $*: pic check"
    head -1 "$T/out"
}

# The whole transcript.
id=$(import "$T/basic.jsonl")
[ "$(q "SELECT count(*) FROM pic_session WHERE id = '$id'")" = 1 ] || fail "no session $id"
for secret in THINK-SECRET META-SECRET SIDECHAIN-SECRET ABANDONED-SECRET SYNTHETIC-SECRET ATTACH-SECRET SYSTEM-SECRET; do
    if sqlite3 "$DB" .dump | grep -q "$secret"; then fail "imported $secret"; fi
done
printf 'PASS: sidechains, thinking, meta, synthetic, attachment, system and abandoned-branch records are left out\n'

# Output: ids and counts only.
grep -q question "$T/out" && fail "output carries transcript text"
grep -q '^requests 5, tool calls 8 structured, 2 as text$' "$T/out" || fail "counts: $(cat "$T/out")"
grep -q '^context [0-9][0-9]* tokens (pic estimate: chars/4 of the messages)$' "$T/out" || fail "tokens: $(cat "$T/out")"
grep -q '^transcript usage 6 tokens (input + cache read + cache write of the last reply)$' "$T/out" || fail "usage: $(cat "$T/out")"
printf 'PASS: import prints the id, counts, the estimate and the transcript usage\n'

# Each tool mapping, with its result and error flag.
want() { # TOOL INPUT RESULT IS_ERROR
    got=$(q "SELECT f.input || '|' || f.result || '|' || f.is_error || '|' || f.state FROM pic_effect f JOIN pic_entry e ON e.seq = f.entry_seq
        JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = '$id' AND f.tool = '$1' AND f.call_id = '$5'")
    [ "$got" = "$2|$3|$4|done" ] || fail "$1 ($5): $got"
}
want bash '{"command":"touch bash-ran","timeout":5}' 'bash out' 0 toolu_bash
want read '{"path":"/x/a.c","offset":2,"limit":3}' 'line two' 0 toolu_read
want edit '{"path":"/x/a.c","edits":[{"oldText":"a","newText":"b"}]}' edited 0 toolu_edit
want edit '{"path":"/x/b.c","edits":[{"oldText":"c","newText":"d"},{"oldText":"e","newText":"f"}]}' 'no match' 1 toolu_multi
want write '{"path":"written.txt","content":"hello"}' wrote 0 toolu_write
want grep '{"pattern":"foo","path":"src","glob":"*.c","ignoreCase":true,"context":2,"limit":10}' 'grep out' 0 toolu_grep
want find '{"pattern":"**/*.h","path":"src"}' 'glob out' 0 toolu_glob
printf 'PASS: Bash, Read, Edit, MultiEdit, Write, Grep and Glob become bash, read, edit, write, grep and find\n'

# LS becomes ls; the Agent call beside it is text in the turn, its result
# (an image omitted) text after the ls result.
want ls '{"path":"src"}' "$(printf 'ls out\n\n[result: agent said\n[image omitted]]')" 0 toolu_ls
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' AND effect_id = (SELECT id FROM pic_effect WHERE call_id = 'toolu_ls')" |
    grep -q '^\[result: agent said$' || fail "agent result not after the ls result"
[ "$(q "SELECT json_extract(body, '\$[3].text') FROM pic_entry WHERE seq = (SELECT entry_seq FROM pic_effect WHERE call_id = 'toolu_ls')")" = \
    '[tool Agent: {"description":"look","prompt":"go look"}]' ] || fail "agent call: $(q "SELECT body FROM pic_entry WHERE seq = (SELECT entry_seq FROM pic_effect WHERE call_id = 'toolu_ls')")"
printf 'PASS: LS becomes ls; an unknown tool and its result are text, an image a placeholder\n'

# A turn of only an unknown tool: the call ends that request as text, its
# result opens the next; the user's image is a placeholder.
users=$(q "SELECT group_concat(replace(e.body, char(10), '/'), ' | ') FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id
    WHERE u.session_id = '$id' AND e.kind = 'user'")
[ "$users" = 'first question | second question/[image omitted] | [result: search results] | third question | fourth question' ] ||
    fail "user entries: $users"
answers=$(q "SELECT group_concat(json_extract(e.body, '\$[0].text'), ' | ') FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id
    WHERE u.session_id = '$id' AND e.kind = 'answer'")
[ "$answers" = 'All done. | [tool WebSearch: {"query":"q"}] | Found it. | Third answer. | Fourth answer.' ] || fail "answers: $answers"
printf 'PASS: a turn of only an unknown tool is text in the answer and the next request\n'

# Nothing ran: the bash and write calls are history.
[ ! -e "$WS/bash-ran" ] && [ ! -e "$WS/written.txt" ] || fail "an imported tool call ran"

# The cut: everything before the record with that uuid.
id2=$(import "$T/basic.jsonl" --until u5)
[ "$(q "SELECT count(*) FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = '$id2' AND e.body LIKE '%fourth%'")" = 0 ] ||
    fail "cut: the cut record was imported"
[ "$(q "SELECT json_extract(body, '\$[0].text') FROM pic_entry WHERE seq = (SELECT head_seq FROM pic_session WHERE id = '$id2')")" = 'Third answer.' ] ||
    fail "cut: head"
grep -q '^transcript usage 240 tokens' "$T/out" || fail "cut: usage $(cat "$T/out")"
# A cut between tool calls and their results: the calls are text.
id3=$(import "$T/basic.jsonl" --until r3)
[ "$(q "SELECT count(*) FROM pic_effect f JOIN pic_entry e ON e.seq = f.entry_seq JOIN pic_submission u ON u.id = e.submission_id
    WHERE u.session_id = '$id3'")" = 2 ] || fail "cut: unanswered calls journaled"
grep -q '^requests 1, tool calls 2 structured, 3 as text$' "$T/out" || fail "cut: counts $(cat "$T/out")"
pic import --claude "$T/basic.jsonl" --until nosuch > /dev/null 2> "$T/err" && fail "cut: an unknown uuid was accepted"
grep -q 'no record nosuch' "$T/err" || fail "cut: $(cat "$T/err")"
printf 'PASS: --until imports everything before that record\n'

# Compaction: from the latest compact summary before the cut.
idc=$(import "$T/compact.jsonl")
body=$(q "SELECT group_concat(body, ' ') FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = '$idc'")
case "$body" in *OLD-*|*SUMMARY-ONE*|*MIDDLE-ANSWER*) fail "compact: before the summary: $body" ;; esac
case "$body" in *SUMMARY-TWO*LATE-ANSWER*) ;; *) fail "compact: $body" ;; esac
idc2=$(import "$T/compact.jsonl" --until b2)
body=$(q "SELECT group_concat(body, ' ') FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = '$idc2'")
case "$body" in *OLD-*|*SUMMARY-TWO*) fail "compact cut: $body" ;; esac
case "$body" in *'SUMMARY-ONE of the work so far'*'after the first compaction'*MIDDLE-ANSWER*) ;; *) fail "compact cut: $body" ;; esac
printf 'PASS: a compacted transcript starts from its latest summary before the cut\n'

# The workspace: the transcript's cwd, or --workspace.
(cd "$T" && "$PIC" import --claude "$T/basic.jsonl" > "$T/out2") || fail "cwd: import"
"$PIC" --workspace "$WS" sessions | grep -q "^$(head -1 "$T/out2")" || fail "cwd: not in the transcript's workspace"
mkdir "$T/other"
(cd "$T" && "$PIC" import --claude "$T/basic.jsonl" --workspace "$T/other" > "$T/out3") || fail "--workspace: import"
"$PIC" --workspace "$T/other" sessions | grep -q "^$(head -1 "$T/out3")" || fail "--workspace: not there"
printf 'PASS: the workspace is the transcript cwd unless --workspace names one\n'

# Continued at each API: every tool_use has its result in the next message.
mkdir "$T/log"
"$SERVER" "$T/port" "$T/log" 120 "sse:$S/text.sse" "sse:$here/chat-streams/text.sse" "sse:$here/responses-streams/reasoning_text.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do
    i=$((i + 1))
    [ "$i" -lt 600 ] || fail "server did not start"
    sleep 0.05
done
base="http://127.0.0.1:$(cat "$T/port")"
body() { sed '1,/^\r*$/d' "$T/log/$1.req" > "$T/body$1.json"; printf '%s' "$T/body$1.json"; }

pic submit next1 'go on' --session "$id" > /dev/null
pic run --model anthropic/m --api-url "$base/v1/messages" 2> "$T/err" || fail "anthropic: $(cat "$T/err")"
b=$(body 1)
pairs=$(sqlite3 :memory: "WITH m AS (SELECT key k, value v FROM json_each(readfile('$b'), '\$.messages')),
  c AS (SELECT m.k, CASE WHEN x.type = 'object' THEN json_extract(x.value, '\$.type') END t,
          CASE WHEN x.type = 'object' THEN coalesce(json_extract(x.value, '\$.id'), json_extract(x.value, '\$.tool_use_id')) END id
        FROM m, json_each(m.v, '\$.content') x)
  SELECT (SELECT count(*) FROM c WHERE t = 'tool_use') || ' ' ||
    (SELECT count(*) FROM c u WHERE t = 'tool_use' AND NOT EXISTS (SELECT 1 FROM c r WHERE r.t = 'tool_result' AND r.k = u.k + 1 AND r.id = u.id)) || ' ' ||
    (SELECT count(*) FROM c r WHERE t = 'tool_result' AND NOT EXISTS (SELECT 1 FROM c u WHERE u.t = 'tool_use' AND u.k = r.k - 1 AND u.id = r.id))")
[ "$pairs" = '8 0 0' ] || fail "anthropic: tool_use/tool_result pairs: $pairs"
pic check > /dev/null || fail "anthropic: check after the reply"
[ ! -e "$WS/bash-ran" ] && [ ! -e "$WS/written.txt" ] || fail "anthropic: an imported tool call ran"
printf 'PASS: the imported conversation continues at the Messages API with its tool calls paired\n'

pic submit next2 'go on' --session "$id2" > /dev/null
pic run --model openrouter/test/model --api-url "$base/v1/chat/completions" 2> "$T/err" || fail "chat: $(cat "$T/err")"
b=$(body 2)
pairs=$(sqlite3 :memory: "WITH m AS (SELECT key k, value v FROM json_each(readfile('$b'), '\$.messages')),
  u AS (SELECT m.k, json_extract(x.value, '\$.id') id FROM m, json_each(m.v, '\$.tool_calls') x),
  r AS (SELECT k, json_extract(v, '\$.tool_call_id') id FROM m WHERE json_extract(v, '\$.role') = 'tool')
  SELECT (SELECT count(*) FROM u) || ' ' ||
    (SELECT count(*) FROM u WHERE NOT EXISTS (SELECT 1 FROM r WHERE r.id = u.id AND r.k > u.k)) || ' ' ||
    (SELECT count(*) FROM r WHERE NOT EXISTS (SELECT 1 FROM u WHERE u.id = r.id AND u.k < r.k))")
[ "$pairs" = '8 0 0' ] || fail "chat: tool_calls/tool pairs: $pairs"
printf 'PASS: and at the Chat Completions API\n'

pic submit next3 'go on' --session "$id3" > /dev/null
pic run --model openai/test-model --api-url "$base/v1/responses" 2> "$T/err" || fail "responses: $(cat "$T/err")"
b=$(body 3)
pairs=$(sqlite3 :memory: "WITH i AS (SELECT json_extract(value, '\$.type') t, json_extract(value, '\$.call_id') id FROM json_each(readfile('$b'), '\$.input'))
  SELECT (SELECT count(*) FROM i WHERE t = 'function_call') || ' ' ||
    (SELECT count(*) FROM i a WHERE t = 'function_call' AND NOT EXISTS (SELECT 1 FROM i o WHERE o.t = 'function_call_output' AND o.id = a.id)) || ' ' ||
    (SELECT count(*) FROM i o WHERE t = 'function_call_output' AND NOT EXISTS (SELECT 1 FROM i a WHERE a.t = 'function_call' AND a.id = o.id))")
[ "$pairs" = '2 0 0' ] || fail "responses: function_call pairs: $pairs"
pic check > /dev/null || fail "check after the replies"
printf 'PASS: and at the Responses API\n'
