#!/bin/bash

set -euo pipefail

frame_rate="${1:-30}"
output_file="${2:-output.mp4}"

rm -f output.pdf
temp_dir=$(mktemp -d)
counter=1

cleanup() {
  rm -rf "$temp_dir"
}
trap cleanup EXIT

# Step 1: Read SVG blobs from stdin and write to files
while IFS= read -r svg_blob; do
  echo "$svg_blob" > "$temp_dir/frame_$(printf "%09d" "$counter").svg"
  counter=$((counter + 1))
done

# Step 2: Parallel conversion
export temp_dir  # export so subprocesses can use it

convert_svg_to_png() {
  svg_file="$1"
  base_name=$(basename "$svg_file" .svg)
  png_file="$temp_dir/$base_name.png"
  rsvg-convert --format=png --output="$png_file" "$svg_file"
}

export -f convert_svg_to_png

total_frames=$(find "$temp_dir" -name 'frame_*.svg' | wc -l)

# Use find + sort + xargs to parallelize
find "$temp_dir" -name 'frame_*.svg' | sort -V | \
  xargs -n 1 -P "$(sysctl -n hw.ncpu)" -I {} bash -c 'convert_svg_to_png "$@"' _ {}

echo "Converted $total_frames frames."

# Step 3: Generate video
ffmpeg -framerate "$frame_rate" -i "$temp_dir/frame_%09d.png" \
       -c:v libx264 -pix_fmt yuv420p \
       "$output_file" -y \
       -hide_banner -loglevel warning
