#!/usr/bin/env fish

# Script to remove all image_path references from Rust code

echo "🧹 Cleaning up image_path references..."

# Backup original files first
echo "📦 Creating backups..."
set backup_dir "backup_before_image_path_removal_$(date +%Y%m%d_%H%M%S)"
mkdir -p $backup_dir

for file in src/models.rs src/db/events.rs src/handlers/events.rs src/upload.rs
    if test -f $file
        cp $file $backup_dir/
        echo "  ✓ Backed up $file"
    end
end

echo ""
echo "🔧 Removing image_path references..."

# Function to safely remove lines containing image_path
function remove_image_path_lines
    set file $argv[1]
    if test -f $file
        echo "  Processing $file..."
        
        # Remove lines that contain image_path (struct fields, variables, etc.)
        sed -i '/image_path/d' $file
        
        # Also remove any trailing commas that might be left hanging
        sed -i '/^[[:space:]]*,$/d' $file
        
        echo "    ✓ Removed image_path references from $file"
    else
        echo "    ⚠️  File $file not found"
    end
end

# Process each file
remove_image_path_lines "src/models.rs"
remove_image_path_lines "src/handlers/events.rs" 
remove_image_path_lines "src/upload.rs"

# For events.rs, we need more careful handling of SQL queries
echo "  Processing src/db/events.rs (SQL queries)..."
if test -f "src/db/events.rs"
    # Remove image_path from SQL UPDATE/INSERT statements and adjust parameter numbers
    sed -i 's/, image_path = \$[0-9][0-9]*//g' src/db/events.rs
    sed -i 's/image_path = \$[0-9][0-9]*,//g' src/db/events.rs
    sed -i 's/image_path = \$[0-9][0-9]*//g' src/db/events.rs
    sed -i 's/, image_path//g' src/db/events.rs
    sed -i 's/image_path,//g' src/db/events.rs
    sed -i '/image_path/d' src/db/events.rs
    
    echo "    ✓ Cleaned SQL queries in src/db/events.rs"
else
    echo "    ⚠️  File src/db/events.rs not found"
end

echo ""
echo "🔍 Checking for remaining references..."
set remaining (grep -r "image_path" src/ 2>/dev/null | wc -l)

if test $remaining -eq 0
    echo "✅ All image_path references removed successfully!"
else
    echo "⚠️  Found $remaining remaining references:"
    grep -r "image_path" src/ --color=always
    echo ""
    echo "You may need to manually review these remaining references."
end

echo ""
echo "🧪 Running cargo check..."
if cargo check
    echo "✅ Code compiles successfully!"
else
    echo "❌ Compilation errors found. You may need to:"
    echo "   - Fix parameter indices in SQL queries"
    echo "   - Remove trailing commas"
    echo "   - Update function signatures"
    echo ""
    echo "💾 Your original files are backed up in: $backup_dir"
end

echo ""
echo "🎉 Cleanup complete!"
echo "💾 Backups saved in: $backup_dir"
echo "🔧 Next steps:"
echo "   1. Review any remaining compilation errors"
echo "   2. Test your application"
echo "   3. Remove backup directory when satisfied"
