#!/usr/bin/env bash
# Rebuilds the test images and runs them through the live Koldflux image-to-text tool, then scores every run.
# Usage: bash test-run.sh <photo.jpg> <work dir>
# Needs: node with Playwright (npm i playwright, or PLAYWRIGHT_MODULE=<path to playwright>), python3; crop.py also needs Pillow.
# The photo we used: "Mount Two Top, Henrys Lake Mountains, Idaho.jpg" from Wikimedia Commons (CC0 1.0).
# Exit 0 only if every step ran; without Pillow the crop retries are skipped and the exit is 3.
set -u
here="$(cd "$(dirname "$0")" && pwd)"
photo="${1:-}"; work="${2:-}"; status=0
if [ -z "$photo" ] || [ -z "$work" ]; then echo "usage: bash test-run.sh photo.jpg workdir"; exit 2; fi
if [ ! -s "$photo" ]; then echo "missing or empty photo: $photo"; exit 1; fi
mkdir -p "$work/in" "$work/out"
node "$here/render.cjs" "$here/cases.json" "$photo" "$work/in" || exit 1
# remove crops and crop scores left by an earlier run, so a failed crop.py cannot reuse them
rm -f "$work/in/chat-bubble-crop.png" "$work/in/text-over-photo-crop.png" "$work/out/tool-runs-crop.json"
python3 -B "$here/crop.py" "$work/in" || { echo "crop.py failed (Pillow missing?); the two crop retries are skipped"; status=3; }
: > "$work/in/edge-empty.png"; printf 'not a picture\r\n' > "$work/in/edge-not-image.png"
python3 -B -c 'import sys,zlib,struct
c=lambda t,d: struct.pack(">I",len(d))+t+d+struct.pack(">I",zlib.crc32(t+d))
raw=b"".join(b"\0"+b"\xff"*2400 for _ in range(600))
open(sys.argv[1],"wb").write(b"\x89PNG\r\n\x1a\n"+c(b"IHDR",struct.pack(">IIBBBBB",800,600,8,2,0,0,0))+c(b"IDAT",zlib.compress(raw))+c(b"IEND",b""))' "$work/in/edge-blank.png" || status=1
node "$here/run-tool.cjs" "$here/cases.json" "$work/in" "$work/out/tool-runs.json" || exit 1
if [ -s "$work/in/chat-bubble-crop.png" ] && [ -s "$work/in/text-over-photo-crop.png" ]; then
  node "$here/run-tool.cjs" "$here/cases-crop.json" "$work/in" "$work/out/tool-runs-crop.json" || status=1
fi
node "$here/run-tool.cjs" "$here/cases-edge.json" "$work/in" "$work/out/tool-runs-edge.json" || status=1
python3 -B "$here/score.py" "$here/cases.json" "$work/out/tool-runs.json" || status=1
if [ -s "$work/out/tool-runs-crop.json" ]; then python3 -B "$here/score.py" "$here/cases-crop.json" "$work/out/tool-runs-crop.json" || status=1; fi
python3 -B "$here/score.py" "$here/cases-edge.json" "$work/out/tool-runs-edge.json" || status=1
exit $status
