#!/usr/bin/env bash

set -e

# Script to convert original images to optimized WebP format
# Run this script from the images-source directory
# Source files: ./ (current directory)
# Output files: ../images/

SOURCE_DIR="."
OUTPUT_DIR="../images"
ITEM_SIZE="256x256"

echo "🔄 Starting image conversion..."
echo "   Source: $SOURCE_DIR"
echo "   Output: $OUTPUT_DIR"
echo ""

for category in items locations npcs interactables characters placeholder; do
    src="$SOURCE_DIR/$category"
    out="$OUTPUT_DIR/$category"
    
    if [[ ! -d "$src" ]]; then
        echo "⚠️  Skipping $category (source not found)"
        continue
    fi
    
    mkdir -p "$out"
    echo "📂 Processing $category..."
    
    find "$src" -maxdepth 1 -type f \( -iname "*.png" -o -iname "*.jpg" -o -iname "*.jpeg" \) | while read -r img; do
        filename="${img##*/}"
        base="${filename%.*}"
        out_file="$out/$base.webp"
        
        if [[ -f "$out_file" ]]; then
            echo "  ✔ Exists: $base.webp"
            continue
        fi
        
        if [[ "$category" == "items" || "$category" == "placeholder" ]]; then
            # Special processing for items: remove white background and resize
            echo "  ➜ Converting item: $filename"
            tmp="/tmp/${base}_clean.png"
            convert "$img" -fuzz 10% -transparent white -resize "$ITEM_SIZE" "$tmp"
            cwebp "$tmp" -q 85 -o "$out_file" >/dev/null
            rm "$tmp"
        else
            # Standard conversion for other categories
            echo "  ➜ Converting: $filename"
            cwebp "$img" -q 85 -o "$out_file" >/dev/null
        fi
    done
done

echo ""
echo "✨ Done! WebP files generated in $OUTPUT_DIR"
