#!/usr/bin/env bash

set -euo pipefail

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

project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
helper="$project_root/config/dot/quickshell/scripts/screen-intelligence"
fixture_dir="$(mktemp -d)"
trap 'rm -rf "$fixture_dir"' EXIT

[[ -x "$helper" ]] || fail 'recognition helper is missing or not executable'
command -v magick >/dev/null || fail 'ImageMagick is required to build the OCR fixture'

probe="$($helper probe)"
jq -e '.tesseract == true and .zbar == true' <<<"$probe" >/dev/null \
    || fail 'Tesseract and ZBar are not ready'

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

result="$($helper analyze-file "$fixture")"
jq -e '.ok == true' <<<"$result" >/dev/null || fail "recognition failed: $(jq -r .error <<<"$result")"
text="$(jq -r .text <<<"$result" | tr '\n' ' ' | tr -s ' ')"
[[ "$text" == *'PANAMA SCREEN INTELLIGENCE'* ]] \
    || fail "literal fixture text was not recognized: $text"

printf 'screen intelligence helper contract: PASS\n'
