#!/bin/bash

# Auto-Fix All Linter Errors Script for Wasot Compiler
# Automatically fixes code formatting, clippy warnings, and other common issues

set -e

echo "🔧 Auto-Fixing All Linter Errors"
echo "================================="

# Check if we're in the right directory
if [ ! -f "Cargo.toml" ]; then
    echo "❌ Error: This script must be run from the project root directory"
    exit 1
fi

# Track overall success
OVERALL_SUCCESS=0

# Function to run a fix command and track results
run_fix() {
    local name="$1"
    local cmd="$2"
    local description="$3"
    
    echo ""
    echo "🔧 $name"
    echo "$(printf '%.0s-' {1..50})"
    echo "📝 $description"
    
    if eval "$cmd"; then
        echo "✅ $name: COMPLETED"
    else
        echo "❌ $name: FAILED"
        OVERALL_SUCCESS=1
    fi
}

# 1. Format Code
run_fix "Code Formatting" \
    "cargo fmt --all" \
    "Formatting all Rust code to standard style"

# 2. Fix Clippy Issues (Safe fixes only)
run_fix "Clippy Auto-Fix (Safe)" \
    "cargo clippy --all-targets --all-features --fix --allow-dirty --allow-staged" \
    "Automatically fixing safe clippy warnings"

# 3. Fix Compiler Suggestions
run_fix "Compiler Suggestions" \
    "cargo fix --all-targets --allow-dirty --allow-staged" \
    "Applying compiler-suggested fixes"

# 4. Fix Unsafe Clippy Issues (More aggressive)
echo ""
echo "🔧 Clippy Auto-Fix (Aggressive)"
echo "$(printf '%.0s-' {1..50})"
echo "📝 Attempting to fix more aggressive clippy warnings"
echo "⚠️  This may make more significant changes to your code"

read -p "Do you want to apply aggressive clippy fixes? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if cargo clippy --all-targets --all-features --fix --allow-dirty --allow-staged -- -W clippy::all -W clippy::pedantic; then
        echo "✅ Aggressive Clippy Fixes: COMPLETED"
    else
        echo "❌ Aggressive Clippy Fixes: FAILED"
        OVERALL_SUCCESS=1
    fi
else
    echo "⏭️  Skipping aggressive clippy fixes"
fi

# 5. Remove Unused Imports and Dead Code
run_fix "Remove Unused Code" \
    "cargo fix --all-targets --allow-dirty --allow-staged" \
    "Removing unused imports and dead code"

# 6. Format Again (in case fixes introduced formatting issues)
run_fix "Final Formatting" \
    "cargo fmt --all" \
    "Final formatting pass after all fixes"

# 7. Update Dependencies (if requested)
echo ""
echo "🔧 Dependency Updates"
echo "$(printf '%.0s-' {1..50})"
echo "📝 Updating dependencies to latest compatible versions"
echo "⚠️  This may change your Cargo.lock file"

read -p "Do you want to update dependencies? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if cargo update; then
        echo "✅ Dependency Updates: COMPLETED"
    else
        echo "❌ Dependency Updates: FAILED"
        OVERALL_SUCCESS=1
    fi
else
    echo "⏭️  Skipping dependency updates"
fi

# 8. Remove Unused Dependencies (if cargo-machete is available)
if command -v cargo-machete &> /dev/null; then
    echo ""
    echo "🔧 Unused Dependencies Check"
    echo "$(printf '%.0s-' {1..50})"
    echo "📝 Checking for unused dependencies"
    
    # Run cargo-machete and capture output
    if UNUSED_DEPS=$(cargo machete 2>&1); then
        if echo "$UNUSED_DEPS" | grep -q "unused dependencies"; then
            echo "⚠️  Found unused dependencies:"
            echo "$UNUSED_DEPS"
            echo ""
            echo "💡 Please manually remove unused dependencies from Cargo.toml"
            echo "   or add them to [package.metadata.cargo-machete] ignored list"
        else
            echo "✅ No unused dependencies found"
        fi
    else
        echo "❌ Failed to check unused dependencies"
    fi
else
    echo ""
    echo "📦 Installing cargo-machete for unused dependency checking..."
    if cargo install cargo-machete; then
        echo "✅ cargo-machete installed successfully"
    else
        echo "❌ Failed to install cargo-machete"
    fi
fi

# 9. Final Validation
echo ""
echo "🔍 Final Validation"
echo "$(printf '%.0s-' {1..50})"
echo "📝 Running final checks to ensure everything compiles"

if cargo check --all-targets --all-features; then
    echo "✅ Final Validation: PASSED"
else
    echo "❌ Final Validation: FAILED"
    OVERALL_SUCCESS=1
fi

# 10. Run Tests
echo ""
echo "🧪 Test Verification"
echo "$(printf '%.0s-' {1..50})"
echo "📝 Running tests to ensure fixes didn't break anything"

if cargo test --all-features; then
    echo "✅ Test Verification: PASSED"
else
    echo "❌ Test Verification: FAILED"
    echo "⚠️  Some fixes may have broken functionality"
    OVERALL_SUCCESS=1
fi

# 11. Final Summary
echo ""
echo "🎯 Auto-Fix Summary"
echo "==================="

if [ $OVERALL_SUCCESS -eq 0 ]; then
    echo "🎉 All auto-fixes completed successfully!"
    echo ""
    echo "✅ Your code has been automatically improved:"
    echo "   - Code formatting applied"
    echo "   - Safe clippy warnings fixed"
    echo "   - Compiler suggestions applied"
    echo "   - Unused code removed"
    echo "   - All tests passing"
    echo ""
    echo "🔧 Next steps:"
    echo "   - Review the changes with: git diff"
    echo "   - Run full linting: ./scripts/ci/linter.sh"
    echo "   - Commit your improvements: git add . && git commit -m 'Auto-fix linter issues'"
else
    echo "⚠️  Some auto-fixes failed or need manual attention"
    echo ""
    echo "🔧 Manual fixes may be needed for:"
    echo "   - Complex clippy warnings"
    echo "   - Dependency conflicts"
    echo "   - Test failures"
    echo "   - Unused dependencies"
    echo ""
    echo "💡 Run the linter to see remaining issues:"
    echo "   ./scripts/ci/linter.sh"
fi

echo ""
echo "📊 Changed Files:"
git diff --name-only HEAD || echo "   (No git repository or no changes)"

echo ""
echo "🎨 Code Quality Tools Used:"
echo "   - cargo fmt (code formatting)"
echo "   - cargo clippy (linting and fixes)"
echo "   - cargo fix (compiler suggestions)"
echo "   - cargo update (dependency updates)"
echo "   - cargo-machete (unused dependency detection)"

exit $OVERALL_SUCCESS