#!/usr/bin/env bash

set -e

# Set size for item icons (example: 256x256 or 128x128)
ITEM_SIZE="256x256"

echo "Starting conversion..."

find . -type d -name "original" | while read -r orig_dir; do
    echo "📂 Folder: $orig_dir"

    out_dir="$(dirname "$orig_dir")"

    # Check if this is the items/original folder
    is_items_folder=false
    if [[ "$orig_dir" == *"/items/original" ]]; then
        is_items_folder=true
        echo "  🔧 Applying item-specific processing (remove white background, resize)"
    fi

    # Process images in original folder
    find "$orig_dir" -maxdepth 1 -type f \( -iname "*.png" -o -iname "*.jpg" -o -iname "*.jpeg" \) | \
    while read -r img; do

        filename="$(basename "$img")"
        base="${filename%.*}"
        out_file="$out_dir/$base.webp"

        if [[ -f "$out_file" ]]; then
            echo "  ✔ Skipping existing: $out_file"
            continue
        fi

        # If this is an item icon, preprocess it
        if [[ "$is_items_folder" = true ]]; then
            echo "  ➜ Processing item: $filename"

            tmp_png="/tmp/${base}_clean.png"

            # 1. Remove white background using ImageMagick
            convert "$img" -fuzz 10% -transparent white "$tmp_png"

            # 2. Resize to smaller square
            convert "$tmp_png" -resize "$ITEM_SIZE" "$tmp_png"

            # 3. Convert to WebP
            cwebp "$tmp_png" -q 85 -o "$out_file" >/dev/null

            rm "$tmp_png"
        
        else
            # Standard conversion for other folders
            echo "  ➜ Converting: $filename → $out_file"
            cwebp "$img" -q 85 -o "$out_file" >/dev/null
        fi

    done
done

echo "✨ Done! Missing files created, with special processing for items."
