#!/bin/bash
# Mutation testing helper script for local development

set -e

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Default values
MODE="changed"
BASE_BRANCH="main"

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --mode)
            MODE="$2"
            shift 2
            ;;
        --base)
            BASE_BRANCH="$2"
            shift 2
            ;;
        --help)
            echo "Usage: $0 [options]"
            echo ""
            echo "Options:"
            echo "  --mode MODE    Testing mode: changed|critical|full|file (default: changed)"
            echo "  --base BRANCH  Base branch for comparison (default: main)"
            echo "  --help         Show this help message"
            echo ""
            echo "Modes:"
            echo "  changed   - Test only files changed from base branch"
            echo "  critical  - Test critical modules (core, exceptions, resilience)"
            echo "  full      - Run full mutation testing suite"
            echo "  file      - Test a specific file (pass as additional argument)"
            echo ""
            echo "Examples:"
            echo "  $0                                    # Test changed files"
            echo "  $0 --mode critical                    # Test critical modules"
            echo "  $0 --mode file src/mymodule.py        # Test specific file"
            exit 0
            ;;
        *)
            FILE_TO_TEST="$1"
            shift
            ;;
    esac
done

# Export environment variables for optimized testing
export CI=true
export PYTHONDONTWRITEBYTECODE=1
export PYTEST_CURRENT_TEST=skip

echo -e "${BLUE}🧬 Mutation Testing Runner${NC}"
echo -e "${BLUE}Mode: $MODE${NC}"
echo ""

# Function to run mutation test and display results
run_mutation_test() {
    local start_time=$(date +%s)

    echo -e "${YELLOW}⏳ Running mutation tests...${NC}"

    # Run the mutation test command passed as arguments
    if uv run mutmut run "$@"; then
        echo -e "${GREEN}✅ Mutation testing completed${NC}"
    else
        echo -e "${YELLOW}⚠️ Some mutations survived${NC}"
    fi

    local end_time=$(date +%s)
    local duration=$((end_time - start_time))

    # Display results
    echo ""
    echo -e "${BLUE}📊 Results Summary:${NC}"
    uv run mutmut show 2>/dev/null | grep -E "🎉|🙁|⏰|🤔|🔇" || true

    echo ""
    echo -e "${BLUE}⏱️ Duration: ${duration} seconds${NC}"

    # Show how to view detailed results
    echo ""
    echo -e "${BLUE}💡 Tips:${NC}"
    echo "  • View specific mutation: uv run mutmut show <id>"
    echo "  • Generate HTML report: uv run mutmut html"
    echo "  • Apply a mutation: uv run mutmut apply <id>"
}

case "$MODE" in
    changed)
        # Test only changed files
        echo -e "${BLUE}📝 Detecting changed files from $BASE_BRANCH...${NC}"

        # Generate patch file
        git diff origin/$BASE_BRANCH...HEAD -- '*.py' > /tmp/mutation_patch.patch

        if [ ! -s /tmp/mutation_patch.patch ]; then
            echo -e "${GREEN}✅ No Python files changed${NC}"
            exit 0
        fi

        echo "Changed files:"
        git diff --name-only origin/$BASE_BRANCH...HEAD -- '*.py' | sed 's/^/  • /'
        echo ""

        run_mutation_test --use-patch-file /tmp/mutation_patch.patch --use-coverage
        ;;

    critical)
        # Test critical modules
        echo -e "${BLUE}🔥 Testing critical modules...${NC}"
        echo "  • src/augint_library/core.py"
        echo "  • src/augint_library/exceptions.py"
        echo "  • src/augint_library/resilience.py"
        echo ""

        run_mutation_test \
            --paths-to-mutate="src/augint_library/core.py" \
            --paths-to-mutate="src/augint_library/exceptions.py" \
            --paths-to-mutate="src/augint_library/resilience.py" \
            --use-coverage
        ;;

    full)
        # Run full mutation testing
        echo -e "${YELLOW}⚠️ Running FULL mutation test suite${NC}"
        echo -e "${YELLOW}This may take 40-60 minutes...${NC}"
        echo ""

        # Show a warning and countdown
        for i in 5 4 3 2 1; do
            echo -ne "\rStarting in $i seconds... (Ctrl+C to cancel)"
            sleep 1
        done
        echo -e "\n"

        run_mutation_test --use-coverage
        ;;

    file)
        # Test specific file
        if [ -z "$FILE_TO_TEST" ]; then
            echo -e "${RED}❌ Error: No file specified${NC}"
            echo "Usage: $0 --mode file <path/to/file.py>"
            exit 1
        fi

        if [ ! -f "$FILE_TO_TEST" ]; then
            echo -e "${RED}❌ Error: File not found: $FILE_TO_TEST${NC}"
            exit 1
        fi

        echo -e "${BLUE}📄 Testing single file: $FILE_TO_TEST${NC}"
        echo ""

        run_mutation_test --paths-to-mutate="$FILE_TO_TEST" --use-coverage
        ;;

    *)
        echo -e "${RED}❌ Invalid mode: $MODE${NC}"
        echo "Valid modes: changed, critical, full, file"
        exit 1
        ;;
esac

# Check if any mutations survived and suggest next steps
if uv run mutmut show 2>/dev/null | grep -q "🙁 Survived"; then
    echo ""
    echo -e "${YELLOW}📚 Next Steps:${NC}"
    echo "1. Review surviving mutations: uv run mutmut show"
    echo "2. Add tests to kill surviving mutations"
    echo "3. Re-run mutation testing to verify fixes"
fi
