#!/bin/bash
# ref-sheet.sh — make reference contact sheets for references/<set>/ (see references/README.md).
#
#   scripts/ref-sheet.sh registry <set> <registry-item>   install a HyperFrames registry item into a
#                                                         dark scratch host and snapshot 6 frames
#   scripts/ref-sheet.sh video <set> <file.mp4> <id>      6 evenly spaced frames from a licensed clip
#   scripts/ref-sheet.sh combine <set>                    stack sheets/*.jpg into sheet.jpg (what the judge sees)
#
# Adding a sheet is not enough: record the source in references/<set>/refs.json, then combine.
set -euo pipefail
cd "$(dirname "$0")/.."
HF=$(node -e 'import("../pipeline/hf.mjs").then(m=>console.log(m.HF.join(" ")))' --input-type=module 2>/dev/null || echo "--yes hyperframes@0.8.58")
mode=$1; set_=$2; dir=references/$set_; mkdir -p "$dir/sheets"

case $mode in
registry)
  item=$3; w=$(mktemp -d); trap 'rm -rf "$w"' EXIT
  (cd "$w" && npx $HF add "$item" > add.log 2>&1)
  file=$(cd "$w" && ls compositions/components/*.html compositions/*.html 2>/dev/null | head -1 || true)
  dur=$(grep -o 'data-duration="[0-9.]*"' "$w/add.log" | head -1 | grep -o '[0-9.]*' || true)
  dur=${dur:-$(grep -o 'data-duration="[0-9.]*"' "$w/$file" | head -1 | grep -o '[0-9.]*' || echo 6)}
  cat > "$w/index.html" <<HTML
<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;width:1920px;height:1080px;background:#06090d}</style></head>
<body><div id="root" data-composition-id="main" data-start="0" data-duration="$dur" data-width="1920" data-height="1080" style="position:relative;width:1920px;height:1080px;background:#06090d">
<div data-composition-src="$file" data-start="0" data-track-index="1" data-duration="$dur" data-width="1920" data-height="1080"></div>
</div><script>window.__timelines=window.__timelines||{};</script></body></html>
HTML
  (cd "$w" && npx $HF snapshot . -o out --frames 6 > snap.log 2>&1)
  cp "$w/out/contact-sheet.jpg" "$dir/sheets/$item.jpg"; echo "sheet: $dir/sheets/$item.jpg" ;;
video)
  src=$3; id=$4
  d=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$src")
  ffmpeg -v error -y -i "$src" -vf "fps=6/$d,scale=600:-2,tile=3x2" -frames:v 1 "$dir/sheets/$id.jpg"
  echo "sheet: $dir/sheets/$id.jpg" ;;
combine)
  ls "$dir"/sheets/*.jpg > /dev/null
  args=(); n=0; for f in "$dir"/sheets/*.jpg; do args+=(-i "$f"); n=$((n+1)); done
  if [ "$n" -eq 1 ]; then cp "${args[1]}" "$dir/sheet.jpg"
  else ffmpeg -v error -y "${args[@]}" -filter_complex "$(for i in $(seq 0 $((n-1))); do printf '[%d]scale=1200:-2[s%d];' $i $i; done)$(for i in $(seq 0 $((n-1))); do printf '[s%d]' $i; done)vstack=inputs=$n" "$dir/sheet.jpg"; fi
  echo "sheet: $dir/sheet.jpg ($n references)" ;;
*) sed -n 2,9p "$0"; exit 1 ;;
esac
