#!/usr/bin/env bash
set -euo pipefail

if [[ $# -lt 4 || $# -gt 5 ]]; then
  cat <<'EOF'
Usage:
  bash scripts/stitch_sprite_sheet.sh <frames_dir> <cols> <rows> <output_sheet> [prefix]

Example:
  bash scripts/stitch_sprite_sheet.sh assets/pets/maple/frames 8 9 /tmp/maple-sheet.png maple

Expected input names:
  <frames_dir>/<prefix>-r01-c01.png
  <frames_dir>/<prefix>-r01-c02.png
  ...

Requirements:
  - ffmpeg
EOF
  exit 1
fi

frames_dir=$1
cols=$2
rows=$3
output_sheet=$4
prefix=${5:-frame}

if [[ ! -d "$frames_dir" ]]; then
  echo "error: frames directory not found: $frames_dir" >&2
  exit 1
fi

if ! command -v ffmpeg >/dev/null 2>&1; then
  echo "error: ffmpeg is required" >&2
  exit 1
fi

tmp_dir=$(mktemp -d /tmp/hyperpets-stitch.XXXXXX)
cleanup() {
  rm -rf "$tmp_dir"
}
trap cleanup EXIT

index=0
for ((row = 1; row <= rows; row++)); do
  for ((col = 1; col <= cols; col++)); do
    src="$frames_dir/${prefix}-r$(printf '%02d' "$row")-c$(printf '%02d' "$col").png"
    if [[ ! -f "$src" ]]; then
      echo "error: missing frame: $src" >&2
      exit 1
    fi
    cp "$src" "$tmp_dir/$(printf '%04d' "$index").png"
    index=$(( index + 1 ))
  done
done

ffmpeg -loglevel error -y -framerate 1 -i "$tmp_dir/%04d.png" -frames:v 1 -vf "tile=${cols}x${rows}" "$output_sheet"

echo "sheet written: $output_sheet"
