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

if [[ $# -lt 4 || $# -gt 5 ]]; then
  cat <<'EOF'
Usage:
  bash scripts/split_sprite_sheet.sh <sheet> <cell_width> <cell_height> <output_dir> [prefix]

Example:
  bash scripts/split_sprite_sheet.sh assets/pets/maple/spritesheet.webp 192 208 assets/pets/maple/frames maple

Outputs:
  <output_dir>/<prefix>-r01-c01.png
  <output_dir>/<prefix>-r01-c02.png
  ...

Requirements:
  - ffmpeg
  - ffprobe
EOF
  exit 1
fi

sheet=$1
cell_width=$2
cell_height=$3
output_dir=$4
prefix=${5:-frame}

if [[ ! -f "$sheet" ]]; then
  echo "error: sheet not found: $sheet" >&2
  exit 1
fi

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

sheet_width=$(ffprobe -v error -select_streams v:0 -show_entries stream=width -of csv=p=0 "$sheet")
sheet_height=$(ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=p=0 "$sheet")

if (( sheet_width % cell_width != 0 )); then
  echo "error: sheet width $sheet_width is not divisible by cell width $cell_width" >&2
  exit 1
fi

if (( sheet_height % cell_height != 0 )); then
  echo "error: sheet height $sheet_height is not divisible by cell height $cell_height" >&2
  exit 1
fi

cols=$(( sheet_width / cell_width ))
rows=$(( sheet_height / cell_height ))

mkdir -p "$output_dir"

for ((row = 0; row < rows; row++)); do
  for ((col = 0; col < cols; col++)); do
    x=$(( col * cell_width ))
    y=$(( row * cell_height ))
    out="$output_dir/${prefix}-r$(printf '%02d' $((row + 1)))-c$(printf '%02d' $((col + 1))).png"
    ffmpeg -loglevel error -y -i "$sheet" -frames:v 1 -vf "crop=${cell_width}:${cell_height}:${x}:${y}" "$out"
  done
done

echo "split complete: ${rows} rows x ${cols} cols -> $output_dir"
