#!/usr/bin/env bash

set -euo pipefail

fail() {
    printf 'screen intelligence contract: %s\n' "$1" >&2
    exit 1
}

fixture_dir="$(mktemp -d)"
cleanup() {
    qs ipc call screen-intelligence close >/dev/null 2>&1 || true
    qs ipc call capture close >/dev/null 2>&1 || true
    rm -rf "$fixture_dir"
}
trap cleanup EXIT

qs ipc show | rg -q '^target screen-intelligence$' || fail 'screen-intelligence IPC target is missing'

status="$(qs ipc call screen-intelligence status)"
jq -e '.phase == "idle" and (.ocrReady | type == "boolean") and (.codeReady | type == "boolean")' <<<"$status" >/dev/null \
    || fail 'readiness status is malformed'

fixture="$fixture_dir/panama-live-ocr.png"
magick -size 1600x260 xc:white \
    -gravity center -fill black -font DejaVu-Sans -pointsize 72 \
    -annotate 0 'PANAMA LIVE OCR' "$fixture"

qs ipc call screen-intelligence analyzeFile "$fixture" >/dev/null
for _ in $(seq 1 100); do
    status="$(qs ipc call screen-intelligence status)"
    phase="$(jq -r .phase <<<"$status")"
    [[ "$phase" == "ready" || "$phase" == "error" ]] && break
    sleep 0.1
done
[[ "$(jq -r .phase <<<"$status")" == "ready" ]] \
    || fail "fixture recognition did not finish successfully: $(jq -r .error <<<"$status")"
[[ "$(jq -r .text <<<"$status" | tr '\n' ' ')" == *'PANAMA LIVE OCR'* ]] \
    || fail 'live service did not expose recognized fixture text'

qs ipc call screen-intelligence close >/dev/null
[[ "$(qs ipc call screen-intelligence status | jq -r .phase)" == "idle" ]] \
    || fail 'close did not reset recognition state'

qs ipc call screen-intelligence open >/dev/null
for _ in $(seq 1 40); do
    capture_status="$(qs ipc call capture status 2>/dev/null || true)"
    if jq -e '.open == true' <<<"$capture_status" >/dev/null 2>&1; then
        break
    fi
    sleep 0.1
done
jq -e '.open == true and .mode == "selection" and .intelligenceMode == true' <<<"$capture_status" >/dev/null \
    || fail 'direct open did not select Selection + Read mode'

printf 'screen intelligence contract: PASS\n'
