#!/bin/bash
# Batch export all SVG designs to PNG at 300 DPI
#
# Usage: ./scripts/batch-export.sh [category]
# Example: ./scripts/batch-export.sh stickers

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
DESIGNS_DIR="$PROJECT_DIR/designs"

DPI=${DPI:-300}
CATEGORY=${1:-}

echo "🍄 Mycopunk Batch Export"
echo "========================"
echo "DPI: $DPI"
echo ""

# Check for Inkscape
if ! command -v inkscape &> /dev/null; then
    echo "Error: Inkscape not found. Please install Inkscape."
    echo "Ubuntu: sudo apt install inkscape"
    exit 1
fi

count=0
errors=0

# Find all SVG files
find_pattern="$DESIGNS_DIR"
if [ -n "$CATEGORY" ]; then
    find_pattern="$DESIGNS_DIR/$CATEGORY"
    echo "Category: $CATEGORY"
fi

echo ""

for svg in $(find "$find_pattern" -name "*.svg" -type f 2>/dev/null); do
    dir=$(dirname "$svg")
    base=$(basename "$svg" .svg)
    export_dir="$dir/exports/${DPI}dpi"
    output="$export_dir/${base}.png"

    # Skip template files
    if [[ "$dir" == *"templates"* ]]; then
        continue
    fi

    echo "Exporting: $base"

    mkdir -p "$export_dir"

    if inkscape "$svg" \
        --export-type=png \
        --export-dpi="$DPI" \
        --export-background-opacity=0 \
        --export-filename="$output" 2>/dev/null; then
        echo "  ✓ $output"
        ((count++))
    else
        echo "  ✗ Failed"
        ((errors++))
    fi
done

echo ""
echo "========================"
echo "Exported: $count files"
if [ $errors -gt 0 ]; then
    echo "Errors: $errors"
    exit 1
fi
echo "Done!"
