#!/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"
PORTRAIT_SIZE="512x512"

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

for category in items locations npcs interactables characters placeholder static_npcs; 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" || "$category" == "static_npcs" || "$category" == "npcs" ]]; then
            # Special processing for items: remove white background and resize
            echo "  ➜ Converting item: $filename"
            tmp="/tmp/${base}_clean.png"
            if [[ "$category" == "static_npcs" ]]; then
                convert "$img" -fuzz 10% -transparent white -resize "$PORTRAIT_SIZE" "$tmp"
            elif [[ "$category" == "items" || "$category" == "placeholder" ]]; then
                convert "$img" -fuzz 10% -transparent white -resize "$ITEM_SIZE" "$tmp"
            else 
                convert "$img" -fuzz 10% -transparent white "$tmp"
            fi
            cwebp "$tmp" -q 85 -o "$out_file" >/dev/null
            rm "$tmp"
        else
            # Standard conversion for other categories
            # If locations or interactables, crop to 16:9
            tmp="/tmp/${base}_clean.png"
            if [[ "$category" == "locations" || "$category" == "interactables" ]]; then
                convert "$img" -resize "16:9" "$tmp"
            else
                convert "$img" "$tmp"
            fi
            echo "  ➜ Converting: $filename"
            cwebp "$tmp" -q 85 -o "$out_file" >/dev/null
        fi
    done
done

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