#!/bin/bash

# Mutation Testing Script for Wasot Compiler
# Tests the quality of your test suite by introducing mutations

set -e

echo "🧬 Mutation Testing for Wasot Compiler"
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

# Install cargo-mutants if not already installed
if ! command -v cargo-mutants &> /dev/null; then
    echo "📦 Installing cargo-mutants..."
    cargo install cargo-mutants
fi

# Create mutation test configuration
MUTANTS_CONFIG=".mutants.toml"
if [ ! -f "$MUTANTS_CONFIG" ]; then
    echo "📝 Creating mutation test configuration..."
    cat > "$MUTANTS_CONFIG" << 'EOF'
# Mutation testing configuration for Wasot Compiler

# Exclude files that don't need mutation testing
exclude_files = [
    "src/main.rs",
    "src/tests.rs",
    "examples/**",
    "tests/**",
]

# Focus on core parsing logic
examine_files = [
    "src/parser.rs",
    "src/block.rs",
    "src/block_parser.rs",
    "src/params.rs",
    "src/tokenizer.rs",
]

# Timeout for each mutation test
timeout = 60

# Maximum number of mutations to test (0 = unlimited)
max_mutations = 100

# Skip mutations that are likely to be equivalent
skip_equivalent = true

# Test command to run for each mutation
test_command = "cargo test"
EOF
fi

echo "🔬 Running mutation testing..."
echo "This may take several minutes..."
echo ""

# Run mutation testing with progress reporting
cargo mutants \
    --no-shuffle \
    --baseline \
    --timeout 60 \
    --jobs $(nproc) \
    --output target/mutation-report.json \
    --verbose

echo ""
echo "📊 Mutation Testing Results"
echo "==========================="

# Parse and display results
if [ -f "target/mutation-report.json" ]; then
    echo "📄 Detailed report saved to: target/mutation-report.json"
    echo ""
    
    # Extract key metrics using basic tools
    TOTAL_MUTATIONS=$(grep -o '"outcome"' target/mutation-report.json | wc -l)
    CAUGHT_MUTATIONS=$(grep -o '"caught"' target/mutation-report.json | wc -l)
    TIMEOUT_MUTATIONS=$(grep -o '"timeout"' target/mutation-report.json | wc -l)
    UNVIABLE_MUTATIONS=$(grep -o '"unviable"' target/mutation-report.json | wc -l)
    
    if [ "$TOTAL_MUTATIONS" -gt 0 ]; then
        MUTATION_SCORE=$(echo "scale=2; $CAUGHT_MUTATIONS * 100 / $TOTAL_MUTATIONS" | bc -l 2>/dev/null || echo "0")
        
        echo "📈 Mutation Score: ${MUTATION_SCORE}%"
        echo "   - Total mutations: $TOTAL_MUTATIONS"
        echo "   - Caught by tests: $CAUGHT_MUTATIONS"
        echo "   - Timeouts: $TIMEOUT_MUTATIONS"
        echo "   - Unviable: $UNVIABLE_MUTATIONS"
        echo ""
        
        # Assess mutation score
        if (( $(echo "$MUTATION_SCORE >= 80" | bc -l 2>/dev/null) )); then
            echo "✅ Excellent mutation score! Your tests are catching most bugs."
        elif (( $(echo "$MUTATION_SCORE >= 60" | bc -l 2>/dev/null) )); then
            echo "⚠️  Good mutation score, but there's room for improvement."
        else
            echo "❌ Low mutation score. Consider adding more comprehensive tests."
        fi
    else
        echo "⚠️  No mutations were generated or results are incomplete."
    fi
else
    echo "❌ Mutation report not found."
fi

echo ""
echo "🎯 Areas for Improvement"
echo "======================="
echo ""

# Simple mutation testing using manual mutations
echo "🔬 Running simple manual mutation tests..."
echo ""

# Create a temporary directory for manual mutations
TMP_DIR=$(mktemp -d)
ORIGINAL_FILE="src/parser.rs"

if [ -f "$ORIGINAL_FILE" ]; then
    cp "$ORIGINAL_FILE" "$TMP_DIR/original.rs"
    
    # Test 1: Change return value
    echo "🧪 Testing mutation: changing return value..."
    sed 's/return None;/return Some(Default::default());/' "$ORIGINAL_FILE" > "$TMP_DIR/mutated.rs"
    cp "$TMP_DIR/mutated.rs" "$ORIGINAL_FILE"
    
    if cargo test --quiet 2>/dev/null; then
        echo "❌ Mutation not caught: return value change"
    else
        echo "✅ Mutation caught: return value change"
    fi
    
    # Restore original
    cp "$TMP_DIR/original.rs" "$ORIGINAL_FILE"
    
    # Test 2: Change comparison operator
    echo "🧪 Testing mutation: changing comparison operator..."
    sed 's/== '\''.'\''/!= '\''.'\''/g' "$ORIGINAL_FILE" > "$TMP_DIR/mutated.rs"
    cp "$TMP_DIR/mutated.rs" "$ORIGINAL_FILE"
    
    if cargo test --quiet 2>/dev/null; then
        echo "❌ Mutation not caught: comparison operator change"
    else
        echo "✅ Mutation caught: comparison operator change"
    fi
    
    # Restore original
    cp "$TMP_DIR/original.rs" "$ORIGINAL_FILE"
    
    # Test 3: Change string literal
    echo "🧪 Testing mutation: changing string literal..."
    sed 's/"text"/"modified"/g' "$ORIGINAL_FILE" > "$TMP_DIR/mutated.rs"
    cp "$TMP_DIR/mutated.rs" "$ORIGINAL_FILE"
    
    if cargo test --quiet 2>/dev/null; then
        echo "❌ Mutation not caught: string literal change"
    else
        echo "✅ Mutation caught: string literal change"
    fi
    
    # Restore original
    cp "$TMP_DIR/original.rs" "$ORIGINAL_FILE"
fi

# Cleanup
rm -rf "$TMP_DIR"

echo ""
echo "💡 Tips for Better Mutation Testing"
echo "==================================="
echo ""
echo "1. **Add Edge Case Tests**: Test boundary conditions and error cases"
echo "2. **Test Return Values**: Verify functions return expected values"
echo "3. **Test Side Effects**: Ensure functions have correct side effects"
echo "4. **Test Error Handling**: Verify error conditions are handled properly"
echo "5. **Test Complex Logic**: Focus on conditional branches and loops"
echo ""
echo "🔧 To run mutation testing again:"
echo "   cargo mutants"
echo ""
echo "📖 To view detailed mutation report:"
echo "   cat target/mutation-report.json | jq ."
echo ""