#!/bin/bash

# Test Coverage Script for Wasot Compiler
# Generates and displays test coverage report with missing lines

set -e

echo "🧪 Test Coverage Analysis 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-tarpaulin if not already installed
if ! command -v cargo-tarpaulin &> /dev/null; then
    echo "📦 Installing cargo-tarpaulin..."
    cargo install cargo-tarpaulin
fi

# Create coverage directory
mkdir -p target/coverage

echo "🔍 Running test coverage analysis..."
echo "This may take a few minutes..."

# Try running with minimal options to avoid segfaults
echo "🛠️  Attempting coverage analysis with basic configuration..."
if cargo tarpaulin --timeout 60 --line --count --out Html --output-dir target/coverage; then
    echo "✅ Coverage analysis completed successfully!"
else
    echo "⚠️  Standard coverage analysis failed, trying fallback approach..."
    echo "🔧 Running coverage with workaround configuration..."
    
    # Fallback: try without HTML output first
    if cargo tarpaulin --timeout 60 --line --count; then
        echo "✅ Basic coverage analysis completed!"
        echo "📊 Attempting HTML report generation..."
        cargo tarpaulin --timeout 60 --line --count --out Html --output-dir target/coverage --skip-clean || echo "⚠️  HTML report generation failed"
    else
        echo "❌ Tarpaulin coverage analysis failed due to segfault"
        echo "🔧 This is a known issue with tarpaulin and certain Rust code patterns"
        echo ""
        echo "📊 Alternative Coverage Analysis:"
        echo "================================="
        echo "💡 Running regular tests to verify functionality..."
        
        if cargo test --quiet; then
            echo "✅ All tests pass - the code is functional"
            echo ""
            echo "🎯 Coverage Estimation Based on Test Structure:"
            
            # Count test functions and code lines as a rough estimate
            TEST_COUNT=$(grep -r "fn test_" src/ | wc -l)
            TOTAL_LINES=$(find src/ -name "*.rs" | xargs wc -l | tail -1 | awk '{print $1}')
            
            echo "📈 Test functions found: $TEST_COUNT"
            echo "📊 Total source lines: $TOTAL_LINES"
            echo ""
            echo "🔍 Manual coverage analysis suggestions:"
            echo "   - Use 'cargo test --verbose' to see all test names"
            echo "   - Review src/tests.rs for comprehensive unit test coverage"
            echo "   - Check that all public APIs have corresponding tests"
            echo "   - Consider integration tests for CLI functionality"
            echo ""
            echo "⚙️  Alternative tools to try:"
            echo "   - grcov (requires LLVM tools)"
            echo "   - kcov (Linux-specific coverage tool)"
            echo "   - IDE coverage plugins (VS Code, IntelliJ)"
        else
            echo "❌ Tests are failing - fix tests before analyzing coverage"
            exit 1
        fi
    fi
fi

# Generate a summary report only if tarpaulin succeeded
if [ -f "target/coverage/tarpaulin-report.html" ] || command -v cargo-tarpaulin >/dev/null 2>&1; then
    echo ""
    echo "📊 Coverage Summary:"
    echo "==================="

    # Try to get a coverage summary (this might fail if HTML generation failed)
    echo "🔍 Generating coverage summary..."
    if COVERAGE_OUTPUT=$(cargo tarpaulin --timeout 60 --line --count 2>/dev/null); then
        echo "$COVERAGE_OUTPUT" | grep -E "(^\d+\.\d+% coverage|^src/|lines:|branches:)" || echo "Coverage data processed"
        
        # Extract coverage percentage
        COVERAGE=$(echo "$COVERAGE_OUTPUT" | grep -oE '[0-9]+\.[0-9]+% coverage' | head -1 | grep -oE '[0-9]+\.[0-9]+' || echo "0.0")
    else
        echo "⚠️  Could not generate coverage summary due to tarpaulin issues"
        COVERAGE="0.0"
    fi

    echo ""
    echo "🎯 Coverage Analysis Complete!"
    echo "================================"

    # Check if HTML report was generated
    if [ -f "target/coverage/tarpaulin-report.html" ]; then
        echo "📄 Detailed HTML report generated at: target/coverage/tarpaulin-report.html"
        echo "🌐 Open in browser: file://$(pwd)/target/coverage/tarpaulin-report.html"
    else
        echo "⚠️  HTML report not available (generation may have failed)"
    fi
    echo ""

    echo "📈 Current line coverage: ${COVERAGE}%"

    # Set minimum coverage threshold (only check if we have real coverage data)
    if [ "$COVERAGE" != "0.0" ]; then
        MIN_COVERAGE=70.0

        if (( $(echo "$COVERAGE >= $MIN_COVERAGE" | bc -l) )); then
            echo "✅ Coverage meets minimum threshold of ${MIN_COVERAGE}%"
        else
            echo "⚠️  Coverage below minimum threshold of ${MIN_COVERAGE}%"
            echo "🎯 Focus on testing the following areas:"
            echo "   - Parser edge cases"
            echo "   - Error handling paths"
            echo "   - Complex parameter parsing"
            echo "   - Block hierarchies"
        fi
    fi
fi

echo ""
echo "💡 Tips for improving coverage:"
echo "   - Add tests for error conditions"
echo "   - Test edge cases in parsing"
echo "   - Verify all public API functions"
echo "   - Test complex nested structures"
echo ""
echo "🔧 To run coverage for specific modules:"
echo "   cargo tarpaulin --packages wasot-compiler"
echo ""