#!/bin/sh
# Cost: a model's prices come from its catalog entry or models.json (Pi's
# input/output/cacheRead/cacheWrite in USD per Mtok, with tiers), each reply is
# priced as Pi's calculateCost does, and the cost shows in the usage event,
# the Pi export, pic models --json and the conversation's total in
# pic sessions --json.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
here=$(cd "$(dirname "$0")" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-cost.XXXXXX")
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-cost-test-key PIC_MODEL_CATALOG=offline
mkdir "$T/ws" "$T/log"
# Chat Completions usage: prompt_tokens includes the 400 cached ones.
printf '%s\n\n%s\n\n%s\n\n' \
    'data: {"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}' \
    'data: {"id":"c1","choices":[],"usage":{"prompt_tokens":1000,"completion_tokens":50,"total_tokens":1050,"prompt_tokens_details":{"cached_tokens":400}}}' \
    'data: [DONE]' > "$T/chat.sse"
"$SERVER" "$T/port" "$T/log" 60 "sse:$here/streams/text.sse" "sse:$here/streams/text.sse" "sse:$T/chat.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server did not start"; sleep 0.05; done
# text.sse reports input 25, output 12: 25*3/1e6 + 12*15/1e6 = 0.000255 USD.
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[
{"id":"priced","cost":{"input":3,"output":15,"cacheRead":0.3,"cacheWrite":3.75}},
{"id":"free"}]},
"chat":{"baseUrl":"http://127.0.0.1:%s","api":"openai-completions","apiKey":"k","models":[{"id":"c","cost":{"input":1,"output":2,"cacheRead":0.5,"cacheWrite":0}}]}}}' "$(cat "$T/port")" "$(cat "$T/port")" > "$T/models.json"
export PIC_MODELS_FILE="$T/models.json"
pic() { "$PIC" --db "$T/j" --workspace "$T/ws" "$@"; }

pic models --json | grep -q '"id":"priced".*"cost":{"input":3,"output":15,"cacheRead":0.3,"cacheWrite":3.75}' ||
    fail "models.json cost: $(pic models --json | grep priced)"
pic models --json | grep -q '"id":"free".*"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0}' ||
    fail "unpriced model: $(pic models --json | grep free)"
pic models --all --json | grep -q '"id":"claude-opus-4-8".*"cost":{"input":5,"output":25,"cacheRead":0.5,"cacheWrite":6.25' ||
    fail "snapshot cost: $(pic models --all --json | grep opus-4-8)"

pic --json --model fake/priced ask hi > "$T/a.jsonl" 2> "$T/err" || fail "ask: $(cat "$T/err")"
grep -q '"usage":{"input":25,"output":12,.*"cost":{"input":7.5e-05,"output":0.00018,"cacheRead":0,"cacheWrite":0,"total":0.000255}}' "$T/a.jsonl" ||
    fail "usage event cost: $(grep -o '"usage".*' "$T/a.jsonl")"
pic --model fake/free ask hi > /dev/null 2>&1 || fail "ask free"
pic export --pi "$T/pi" > /dev/null 2>&1 || fail "export"
cat "$T"/pi/* "$T"/pi/*/* 2> /dev/null | grep -q '"cost":{"input":7.5e-05,"output":0.00018,"cacheRead":0,"cacheWrite":0,"total":0.000255}' ||
    fail "export cost"
cat "$T"/pi/* "$T"/pi/*/* 2> /dev/null | grep -q '"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}' ||
    fail "export: the unpriced reply costs zero"
# Pi's normalisation: input excludes cached tokens, totalTokens is their sum.
pic --json --model chat/c ask hi > "$T/c.jsonl" 2> "$T/err" || fail "chat ask: $(cat "$T/err")"
grep -q '"usage":{"input":600,"output":50,"cacheRead":400,"cacheWrite":0,"totalTokens":1050,"cost":{"input":0.0006,"output":0.0001,"cacheRead":0.0002,"cacheWrite":0,"total":0.0009}}' "$T/c.jsonl" ||
    fail "chat usage: $(grep -o '"usage".*' "$T/c.jsonl")"
pic export --pi "$T/pi" > /dev/null 2>&1 || fail "export"
cat "$T"/pi/* "$T"/pi/*/* 2> /dev/null | grep -q '"usage":{"input":600,"output":50,"cacheRead":400,"cacheWrite":0,"totalTokens":1050,"cost"' ||
    fail "export chat usage"
pic sessions --json | grep -q '"cost":{"input":7.5e-05,"output":0.00018,"cacheRead":0,"cacheWrite":0,"total":0.000255}' ||
    fail "sessions cost: $(pic sessions --json)"
printf 'PASS: replies carry cost in events, the export, models and sessions\n'
