#!/usr/bin/env zsh

# Check if at least one input file was provided
if [ $# -eq 0 ]; then
    echo "Usage: $0 input1.mp4 [input2.mp4 ...]"
    exit 1
fi

# Process each input file
for input in "$@"; do
    # Skip if file doesn't exist
    if [ ! -f "$input" ]; then
        echo "Error: File '$input' not found"
        continue
    fi

    # Generate output filename by replacing .mp4 with .gif
    output="${input%.*}.gif"
    palette_file="/tmp/palette_$$.png"

    echo "Converting $input to $output..."

    # Generate palette
    ffmpeg -i "$input" -vf "fps=30,palettegen" "$palette_file" || {
        echo "Error generating palette for $input"
        rm -f "$palette_file"
        continue
    }

    # Convert to gif using palette
    ffmpeg -i "$input" -i "$palette_file" -filter_complex "fps=30[x];[x][1:v]paletteuse" "$output" || {
        echo "Error converting $input to gif"
        rm -f "$palette_file"
        continue
    }

    # Clean up palette file
    rm -f "$palette_file"
    echo "Successfully converted $input to $output"
done