#!/usr/bin/env bash
# Render one screen at several points on its timeline and montage them -- the
# P2 gate artifact, and the way to eyeball any animation question later.
#
#   tools/screen-strip main_menu                       # a default spread
#   tools/screen-strip main_menu 0.45 0.6 0.9 1.35     # explicit seconds
#
# Also writes <screen>.rest.png and <screen>.settled.png and reports where they
# differ. That difference is the interesting number: the timeline is expected to
# land EXACTLY on the declared resting pose for every element whose `rest` the
# decoders identify correctly, so a clean run shows a difference confined to the
# elements we know it misses, and nothing else. A difference anywhere else means
# the interpolation is wrong.
set -euo pipefail
cd "${PROJECT_DIR:-/work}"

name="${1:?usage: screen-strip SCREEN [SECONDS...]}"; shift
times=("$@")
[ ${#times[@]} -eq 0 ] && times=(0.45 0.52 0.57 0.62 0.67 0.75 0.90 1.35)
OUT="${OUT:-${TMPDIR:-/tmp}/screen-strip}"
export DISPLAY="${DISPLAY:-:97}"
mkdir -p "$OUT"
[ -d port/.godot ] || godot --headless --path port --import >/dev/null 2>&1

shot() { # shot <godot args...> <outfile>
  local out="${!#}"
  godot --path port --resolution 1280x720 -- "--screen=$name" "${@:1:$#-1}" \
    "--capture=$out" >"$OUT/$name.log" 2>&1
}

labelled=()
for t in "${times[@]}"; do
  shot "--time=$t" "$OUT/$name.t$t.png"
  convert "$OUT/$name.t$t.png" -resize 320x180 -bordercolor gray30 -border 1 \
    -background black -fill white -pointsize 13 label:"t = ${t}s" \
    -gravity center -append "$OUT/$name.lab$t.png"
  labelled+=("$OUT/$name.lab$t.png")
done
montage "${labelled[@]}" -tile 4x -geometry +4+4 -background black "$OUT/$name.strip.png"

shot --pose=rest "$OUT/$name.rest.png"
shot --time=99 "$OUT/$name.settled.png"
convert "$OUT/$name.settled.png" "$OUT/$name.rest.png" -compose difference -composite "$OUT/$name.d.png"
max=$(convert "$OUT/$name.d.png" -format "%[fx:maxima*255]" info:)
convert "$OUT/$name.d.png" -colorspace Gray -threshold 0 "$OUT/$name.m.png"
if [ "${max%.*}" = "0" ]; then
  box="(identical)"
else
  box=$(convert "$OUT/$name.m.png" -trim -format "%wx%h%X%Y" info: 2>/dev/null)
fi
echo "$name: strip -> $OUT/$name.strip.png"
echo "$name: settled timeline vs declared rest -- max ${max}/255, differing region $box"
