#!/usr/bin/env fish

echo "🖼️ MIGRATING ALL IMAGE FORMATS (JPEG, PNG, etc.)"
echo "================================================"

set API_BASE "https://api.rockvilletollandsda.church/api"
set STORAGE_PATH "/media/archive/pocketbase-temp/pocketbase/pb_data/storage/2tz9osuik53a0yh"
set OLD_PB_BASE "https://pocketbase.rockvilletollandsda.church/api"
set UPLOAD_DIR "/opt/rtsda/church-api/uploads/events"

# Get token
set AUTH_RESPONSE (curl -s -X POST $API_BASE/auth/login \
    -H "Content-Type: application/json" \
    -d '{"username": "admin", "password": "Alright8-Reapply-Shrewdly-Platter-Important-Keenness-Banking-Streak-Tactile"}')

set JWT_TOKEN (echo $AUTH_RESPONSE | jq -r '.data.token')
echo "✅ Got token"

# Get events for matching
set NEW_EVENTS (curl -s -H "Authorization: Bearer $JWT_TOKEN" "$API_BASE/events?perPage=500")
echo $NEW_EVENTS | jq '.data.items | map({id, title})' > new_events.json

set OLD_EVENTS (curl -s "$OLD_PB_BASE/collections/events/records?perPage=500")
echo $OLD_EVENTS | jq '.items | map({id, title})' > old_events.json

set uploaded 0
set failed 0

for event_dir in (find $STORAGE_PATH -mindepth 1 -maxdepth 1 -type d -name '[a-z0-9]*')
    set old_id (basename $event_dir)
    
    # Find ANY image file (jpeg, png, gif, webp)
    set image_files (find $event_dir -maxdepth 1 -type f \( -name "*.webp" -o -name "*.jpeg" -o -name "*.jpg" -o -name "*.png" -o -name "*.gif" \) | grep -v "100x100_")
    
    if test (count $image_files) -eq 0
        continue
    end
    
    set image_file $image_files[1]  # Take the first image
    
    # Get old event and find new match
    set old_event (cat old_events.json | jq --arg id "$old_id" '.[] | select(.id == $id)')
    if test -z "$old_event"
        continue
    end
    
    set title (echo $old_event | jq -r '.title')
    set new_event (cat new_events.json | jq --arg title "$title" '.[] | select(.title == $title)')
    
    if test -z "$new_event"
        echo "❌ No match for: $title"
        continue
    end
    
    set new_id (echo $new_event | jq -r '.id')
    set original_filename (basename $image_file)
    set extension (echo $original_filename | sed 's/.*\.//')
    
    # Create WebP filename
    set base_name (echo $original_filename | sed 's/\.[^.]*$//')
    set webp_filename "$new_id-$base_name.webp"
    set webp_path "$UPLOAD_DIR/$webp_filename"
    
    echo "📤 Processing: $title"
    echo "  Source: $original_filename ($extension)"
    echo "  Target: $webp_filename"
    
    # Convert to WebP (works for any input format)
    if convert "$image_file" "$webp_path"
        echo "✅ Converted to WebP"
        
        # Update database
        set current_event (curl -s -H "Authorization: Bearer $JWT_TOKEN" "$API_BASE/events/$new_id")
        
        set simple_filename (echo $webp_filename | sed "s/^$new_id-//")
        set image_path "uploads/events/$webp_filename"
        
        set event_data (echo $current_event | jq --arg img "$simple_filename" --arg imgpath "$image_path" \
            '.data | {
                title: .title,
                description: .description,
                start_time: .start_time,
                end_time: .end_time,
                location: .location,
                location_url: .location_url,
                category: .category,
                recurring_type: .recurring_type,
                is_featured: .is_featured,
                image: $img,
                image_path: $imgpath
            }')
        
        set update_response (curl -s -X PUT \
            -H "Authorization: Bearer $JWT_TOKEN" \
            -H "Content-Type: application/json" \
            -d "$event_data" \
            "$API_BASE/admin/events/$new_id")
        
        set success (echo $update_response | jq -r '.success // false')
        
        if test "$success" = "true"
            echo "✅ SUCCESS: $title"
            set uploaded (math $uploaded + 1)
        else
            echo "❌ DB UPDATE FAILED: $title"
            set failed (math $failed + 1)
        end
    else
        echo "❌ CONVERSION FAILED: $title"
        set failed (math $failed + 1)
    end
    
    echo "---"
    sleep 0.1
end

rm -f new_events.json old_events.json

echo ""
echo "🎉 FINAL RESULTS!"
echo "================="
echo "✅ Successfully converted: $uploaded images"
echo "❌ Failed: $failed images"
echo ""
echo "All images now converted to WebP format!"
