"""
Storm Logger Test Enhancement System
Analyzes existing tests and provides intelligent enhancement suggestions
"""

import ast
import json
import re
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Any
from dataclasses import dataclass, asdict
from enum import Enum

from .coverage_analysis import StormCoverageAnalyzer


class TestIssueType(Enum):
    """Types of test issues that can be detected"""
    INSUFFICIENT_COVERAGE = "insufficient_coverage"
    MISSING_EDGE_CASES = "missing_edge_cases"
    WEAK_ASSERTIONS = "weak_assertions"
    NO_ERROR_TESTING = "no_error_testing"
    MISSING_FIXTURES = "missing_fixtures"
    OUTDATED_PATTERNS = "outdated_patterns"
    PERFORMANCE_GAPS = "performance_gaps"
    INTEGRATION_MISSING = "integration_missing"
    BUSINESS_LOGIC_GAPS = "business_logic_gaps"
    SECURITY_TESTING_GAPS = "security_testing_gaps"


@dataclass
class TestEnhancementSuggestion:
    """Represents a test enhancement suggestion"""
    issue_type: TestIssueType
    severity: str  # "critical", "high", "medium", "low"
    description: str
    suggested_fix: str
    code_example: Optional[str] = None
    file_path: Optional[str] = None
    line_number: Optional[int] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary"""
        return asdict(self)


@dataclass
class TestEnhancementAnalysis:
    """Complete analysis of test enhancement opportunities"""
    test_file: str
    coverage_percentage: float
    suggestions: List[TestEnhancementSuggestion]
    business_impact: str
    priority_score: int
    enhancement_effort: str  # "low", "medium", "high"
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary"""
        return asdict(self)


class StormTestEnhancer:
    """
    Intelligent test enhancement system for Storm Logger
    Uses Storm Logger's business intelligence to prioritize improvements
    """
    
    def __init__(self, project_root: str = "/home/mathew/python-3.10.12-Projects/storm_logger"):
        self.project_root = Path(project_root)
        self.coverage_analyzer = StormCoverageAnalyzer(project_root)
        
        # Storm Logger business-critical patterns
        self.business_critical_patterns = {
            'business_metrics': ['revenue', 'conversion', 'performance', 'roi'],
            'security_compliance': ['sanitize', 'gdpr', 'hipaa', 'pii', 'compliance'],
            'performance_critical': ['6m_logs', 'daedalus', 'rate_limit', 'performance'],
            'enterprise_features': ['django', 'professional', 'enterprise', 'scalability']
        }
        
        # Storm Logger test quality patterns
        self.storm_test_patterns = {
            'fixtures': ['storm_logger', 'temp_log_dir', 'basic_config'],
            'assertions': ['assert_logs_contain', 'assert_performance_metric', 'assert_business_event'],
            'contexts': ['performance_context', 'business_context', 'security_context']
        }
    
    def analyze_test_file(self, test_file_path: str) -> TestEnhancementAnalysis:
        """
        Analyze a test file and provide enhancement suggestions
        
        Args:
            test_file_path: Path to the test file
            
        Returns:
            TestEnhancementAnalysis with suggestions
        """
        test_path = Path(test_file_path)
        
        if not test_path.exists():
            return TestEnhancementAnalysis(
                test_file=test_file_path,
                coverage_percentage=0.0,
                suggestions=[TestEnhancementSuggestion(
                    issue_type=TestIssueType.INSUFFICIENT_COVERAGE,
                    severity="critical",
                    description="Test file does not exist",
                    suggested_fix="Create test file with comprehensive coverage"
                )],
                business_impact="High - Missing test coverage for business-critical functionality",
                priority_score=100,
                enhancement_effort="high"
            )
        
        # Get coverage information
        coverage_info = self._get_coverage_info(test_file_path)
        
        # Parse test file AST
        test_ast = self._parse_test_file(test_file_path)
        
        # Analyze test patterns
        suggestions = []
        suggestions.extend(self._analyze_coverage_gaps(test_file_path, coverage_info))
        suggestions.extend(self._analyze_test_structure(test_ast, test_file_path))
        suggestions.extend(self._analyze_business_logic_coverage(test_ast, test_file_path))
        suggestions.extend(self._analyze_storm_patterns(test_ast, test_file_path))
        
        # Calculate priority and effort
        priority_score = self._calculate_priority_score(suggestions, test_file_path)
        enhancement_effort = self._estimate_enhancement_effort(suggestions)
        business_impact = self._assess_business_impact(suggestions, test_file_path)
        
        return TestEnhancementAnalysis(
            test_file=test_file_path,
            coverage_percentage=coverage_info.get('coverage_percentage', 0.0),
            suggestions=suggestions,
            business_impact=business_impact,
            priority_score=priority_score,
            enhancement_effort=enhancement_effort
        )
    
    def _get_coverage_info(self, test_file_path: str) -> Dict[str, Any]:
        """Get coverage information for the test file"""
        try:
            # Map test file to source file
            source_file = self._map_test_to_source(test_file_path)
            if source_file:
                coverage_analysis = self.coverage_analyzer.analyze_coverage_gaps()
                for module in coverage_analysis.modules:
                    if module.file_path == source_file:
                        return {
                            'coverage_percentage': module.coverage_percentage,
                            'missing_lines': module.missing_lines,
                            'uncovered_functions': module.uncovered_functions
                        }
        except Exception:
            pass
        
        return {'coverage_percentage': 0.0, 'missing_lines': [], 'uncovered_functions': []}
    
    def _map_test_to_source(self, test_file_path: str) -> Optional[str]:
        """Map test file to source file"""
        test_path = Path(test_file_path)
        
        # Common test file patterns
        if test_path.name.startswith('test_'):
            source_name = test_path.name[5:]  # Remove 'test_' prefix
            
            # Look for source file in storm_logger directory
            for source_dir in ['storm_logger', 'storm_logger/core', 'storm_logger/utils', 
                             'storm_logger/console', 'storm_logger/integrations']:
                source_path = self.project_root / source_dir / source_name
                if source_path.exists():
                    return str(source_path)
        
        return None
    
    def _parse_test_file(self, test_file_path: str) -> Optional[ast.AST]:
        """Parse test file into AST"""
        try:
            with open(test_file_path, 'r') as f:
                content = f.read()
            return ast.parse(content)
        except Exception:
            return None
    
    def _analyze_coverage_gaps(self, test_file_path: str, coverage_info: Dict[str, Any]) -> List[TestEnhancementSuggestion]:
        """Analyze coverage gaps and suggest improvements"""
        suggestions = []
        
        coverage_percentage = coverage_info.get('coverage_percentage', 0.0)
        missing_lines = coverage_info.get('missing_lines', [])
        uncovered_functions = coverage_info.get('uncovered_functions', [])
        
        # Low coverage
        if coverage_percentage < 90:
            severity = "critical" if coverage_percentage < 50 else "high"
            suggestions.append(TestEnhancementSuggestion(
                issue_type=TestIssueType.INSUFFICIENT_COVERAGE,
                severity=severity,
                description=f"Coverage is {coverage_percentage:.1f}%, below Storm Logger standard of 90%",
                suggested_fix=f"Add tests for {len(missing_lines)} missing lines and {len(uncovered_functions)} uncovered functions",
                code_example=self._generate_coverage_improvement_example(uncovered_functions),
                file_path=test_file_path
            ))
        
        # Specific uncovered functions
        for func_name in uncovered_functions[:5]:  # Top 5 uncovered functions
            suggestions.append(TestEnhancementSuggestion(
                issue_type=TestIssueType.INSUFFICIENT_COVERAGE,
                severity="medium",
                description=f"Function '{func_name}' is not covered by tests",
                suggested_fix=f"Add comprehensive tests for {func_name} including edge cases",
                code_example=self._generate_function_test_example(func_name),
                file_path=test_file_path
            ))
        
        return suggestions
    
    def _analyze_test_structure(self, test_ast: Optional[ast.AST], test_file_path: str) -> List[TestEnhancementSuggestion]:
        """Analyze test structure and patterns"""
        suggestions = []
        
        if not test_ast:
            return suggestions
        
        # Count test functions
        test_functions = []
        assertion_count = 0
        fixture_usage = []
        
        for node in ast.walk(test_ast):
            if isinstance(node, ast.FunctionDef) and node.name.startswith('test_'):
                test_functions.append(node.name)
                
                # Count assertions in this test
                test_assertions = 0
                for test_node in ast.walk(node):
                    if isinstance(test_node, ast.Call) and isinstance(test_node.func, ast.Name):
                        if test_node.func.id.startswith('assert'):
                            test_assertions += 1
                
                assertion_count += test_assertions
                
                # Check for weak assertions
                if test_assertions < 2:
                    suggestions.append(TestEnhancementSuggestion(
                        issue_type=TestIssueType.WEAK_ASSERTIONS,
                        severity="medium",
                        description=f"Test function '{node.name}' has only {test_assertions} assertion(s)",
                        suggested_fix="Add more specific assertions to validate behavior thoroughly",
                        code_example=self._generate_assertion_example(node.name),
                        file_path=test_file_path,
                        line_number=node.lineno
                    ))
            
            # Check for fixture usage
            if isinstance(node, ast.arg) and node.arg in self.storm_test_patterns['fixtures']:
                fixture_usage.append(node.arg)
        
        # Check for missing Storm Logger fixtures
        if 'storm_logger' not in fixture_usage:
            suggestions.append(TestEnhancementSuggestion(
                issue_type=TestIssueType.MISSING_FIXTURES,
                severity="medium",
                description="Not using Storm Logger test fixtures",
                suggested_fix="Use storm_logger fixture for consistent test setup",
                code_example=self._generate_fixture_example(),
                file_path=test_file_path
            ))
        
        # Check for error testing
        has_error_tests = any('error' in func_name.lower() or 'exception' in func_name.lower() 
                            for func_name in test_functions)
        
        if not has_error_tests:
            suggestions.append(TestEnhancementSuggestion(
                issue_type=TestIssueType.NO_ERROR_TESTING,
                severity="high",
                description="No error/exception testing found",
                suggested_fix="Add tests for error conditions and edge cases",
                code_example=self._generate_error_test_example(),
                file_path=test_file_path
            ))
        
        return suggestions
    
    def _analyze_business_logic_coverage(self, test_ast: Optional[ast.AST], test_file_path: str) -> List[TestEnhancementSuggestion]:
        """Analyze business logic coverage specific to Storm Logger"""
        suggestions = []
        
        if not test_ast:
            return suggestions
        
        # Check for business metrics testing
        has_business_metrics = False
        has_performance_testing = False
        has_security_testing = False
        
        for node in ast.walk(test_ast):
            if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
                method_name = node.func.attr.lower()
                
                # Check for business metrics
                if any(pattern in method_name for pattern in self.business_critical_patterns['business_metrics']):
                    has_business_metrics = True
                
                # Check for performance testing
                if any(pattern in method_name for pattern in self.business_critical_patterns['performance_critical']):
                    has_performance_testing = True
                
                # Check for security testing
                if any(pattern in method_name for pattern in self.business_critical_patterns['security_compliance']):
                    has_security_testing = True
        
        # Suggest missing business logic tests
        if not has_business_metrics and self._is_business_critical_file(test_file_path):
            suggestions.append(TestEnhancementSuggestion(
                issue_type=TestIssueType.BUSINESS_LOGIC_GAPS,
                severity="high",
                description="Missing business metrics testing for business-critical module",
                suggested_fix="Add tests for business event tracking and metrics collection",
                code_example=self._generate_business_metrics_test_example(),
                file_path=test_file_path
            ))
        
        if not has_performance_testing and self._is_performance_critical_file(test_file_path):
            suggestions.append(TestEnhancementSuggestion(
                issue_type=TestIssueType.PERFORMANCE_GAPS,
                severity="high",
                description="Missing performance testing for performance-critical module",
                suggested_fix="Add performance benchmarks and 6M logs/sec validation",
                code_example=self._generate_performance_test_example(),
                file_path=test_file_path
            ))
        
        if not has_security_testing and self._is_security_critical_file(test_file_path):
            suggestions.append(TestEnhancementSuggestion(
                issue_type=TestIssueType.SECURITY_TESTING_GAPS,
                severity="critical",
                description="Missing security testing for security-critical module",
                suggested_fix="Add PII sanitization and compliance validation tests",
                code_example=self._generate_security_test_example(),
                file_path=test_file_path
            ))
        
        return suggestions
    
    def _analyze_storm_patterns(self, test_ast: Optional[ast.AST], test_file_path: str) -> List[TestEnhancementSuggestion]:
        """Analyze adherence to Storm Logger test patterns"""
        suggestions = []
        
        if not test_ast:
            return suggestions
        
        # Check for Storm Logger specific patterns
        uses_storm_assertions = False
        uses_storm_contexts = False
        
        for node in ast.walk(test_ast):
            if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
                method_name = node.func.attr
                
                # Check for Storm assertions
                if any(pattern in method_name for pattern in self.storm_test_patterns['assertions']):
                    uses_storm_assertions = True
                
                # Check for Storm contexts
                if any(pattern in method_name for pattern in self.storm_test_patterns['contexts']):
                    uses_storm_contexts = True
        
        # Suggest Storm Logger patterns
        if not uses_storm_assertions:
            suggestions.append(TestEnhancementSuggestion(
                issue_type=TestIssueType.OUTDATED_PATTERNS,
                severity="medium",
                description="Not using Storm Logger specific test assertions",
                suggested_fix="Use Storm Logger test helpers for better validation",
                code_example=self._generate_storm_assertion_example(),
                file_path=test_file_path
            ))
        
        if not uses_storm_contexts and self._requires_storm_contexts(test_file_path):
            suggestions.append(TestEnhancementSuggestion(
                issue_type=TestIssueType.OUTDATED_PATTERNS,
                severity="medium",
                description="Not using Storm Logger context managers in tests",
                suggested_fix="Use Storm Logger context managers for proper test isolation",
                code_example=self._generate_storm_context_example(),
                file_path=test_file_path
            ))
        
        return suggestions
    
    def _calculate_priority_score(self, suggestions: List[TestEnhancementSuggestion], test_file_path: str) -> int:
        """Calculate priority score based on suggestions and business impact"""
        score = 0
        
        # Base score from severity
        severity_scores = {"critical": 40, "high": 30, "medium": 20, "low": 10}
        for suggestion in suggestions:
            score += severity_scores.get(suggestion.severity, 10)
        
        # Business critical multiplier
        if self._is_business_critical_file(test_file_path):
            score *= 2
        
        # Performance critical multiplier
        if self._is_performance_critical_file(test_file_path):
            score *= 1.5
        
        return min(score, 100)  # Cap at 100
    
    def _estimate_enhancement_effort(self, suggestions: List[TestEnhancementSuggestion]) -> str:
        """Estimate effort required for enhancements"""
        total_suggestions = len(suggestions)
        critical_high = len([s for s in suggestions if s.severity in ["critical", "high"]])
        
        if total_suggestions == 0:
            return "low"
        elif critical_high > 5 or total_suggestions > 15:
            return "high"
        elif critical_high > 2 or total_suggestions > 8:
            return "medium"
        else:
            return "low"
    
    def _assess_business_impact(self, suggestions: List[TestEnhancementSuggestion], test_file_path: str) -> str:
        """Assess business impact of test improvements"""
        critical_issues = [s for s in suggestions if s.severity == "critical"]
        business_issues = [s for s in suggestions if s.issue_type == TestIssueType.BUSINESS_LOGIC_GAPS]
        
        if critical_issues or (business_issues and self._is_business_critical_file(test_file_path)):
            return "High - Critical gaps in business-critical functionality testing"
        elif len(suggestions) > 10:
            return "Medium - Multiple test quality issues affecting reliability"
        else:
            return "Low - Minor improvements to test quality"
    
    def _is_business_critical_file(self, test_file_path: str) -> bool:
        """Check if file is business-critical"""
        business_critical_modules = [
            'business_metrics', 'professional_logger', 'django', 'enterprise'
        ]
        return any(module in test_file_path.lower() for module in business_critical_modules)
    
    def _is_performance_critical_file(self, test_file_path: str) -> bool:
        """Check if file is performance-critical"""
        performance_critical_modules = [
            'logger', 'daedalus', 'performance', 'rate_limit'
        ]
        return any(module in test_file_path.lower() for module in performance_critical_modules)
    
    def _is_security_critical_file(self, test_file_path: str) -> bool:
        """Check if file is security-critical"""
        security_critical_modules = [
            'sanitizer', 'patterns', 'security', 'compliance'
        ]
        return any(module in test_file_path.lower() for module in security_critical_modules)
    
    def _requires_storm_contexts(self, test_file_path: str) -> bool:
        """Check if file requires Storm Logger contexts"""
        return self._is_business_critical_file(test_file_path) or self._is_performance_critical_file(test_file_path)
    
    def _generate_coverage_improvement_example(self, uncovered_functions: List[str]) -> str:
        """Generate example code for coverage improvement"""
        if not uncovered_functions:
            return ""
        
        func_name = uncovered_functions[0] if uncovered_functions else "example_function"
        return f"""
def test_{func_name}(storm_logger):
    \"\"\"Test {func_name} with comprehensive coverage\"\"\"
    # Test normal operation
    result = storm_logger.{func_name}()
    assert result is not None
    
    # Test edge cases
    with pytest.raises(ValueError):
        storm_logger.{func_name}(invalid_param=True)
    
    # Test business logic
    storm_logger.track_business_event("{func_name}_executed", {{"success": True}})
    assert storm_logger.get_business_metrics()["{func_name}_executed"] == 1
"""
    
    def _generate_function_test_example(self, func_name: str) -> str:
        """Generate example test for specific function"""
        return f"""
def test_{func_name}_comprehensive(storm_logger):
    \"\"\"Comprehensive test for {func_name}\"\"\"
    # Test normal operation
    result = storm_logger.{func_name}()
    assert result is not None
    
    # Test with different parameters
    result_with_params = storm_logger.{func_name}(param1="test", param2=42)
    assert result_with_params != result
    
    # Test error conditions
    with pytest.raises(ValueError):
        storm_logger.{func_name}(invalid_param=None)
    
    # Test performance (if applicable)
    import time
    start = time.time()
    storm_logger.{func_name}()
    duration = time.time() - start
    assert duration < 0.001  # Should be very fast
"""
    
    def _generate_assertion_example(self, test_name: str) -> str:
        """Generate example with better assertions"""
        return f"""
def {test_name}(storm_logger):
    \"\"\"Enhanced test with comprehensive assertions\"\"\"
    result = storm_logger.log("Test message")
    
    # Specific assertions
    assert result.status == "success"
    assert result.message == "Test message"
    assert result.timestamp is not None
    assert result.level == "INFO"
    
    # Business metric assertions
    metrics = storm_logger.get_business_metrics()
    assert metrics["log_count"] == 1
    assert metrics["last_log_time"] > 0
"""
    
    def _generate_fixture_example(self) -> str:
        """Generate example using Storm Logger fixtures"""
        return """
def test_with_storm_fixtures(storm_logger, temp_log_dir, basic_config):
    \"\"\"Test using Storm Logger fixtures\"\"\"
    # storm_logger fixture provides configured logger
    # temp_log_dir provides temporary directory
    # basic_config provides test configuration
    
    storm_logger.info("Test message")
    
    # Verify log file creation
    log_files = list(temp_log_dir.glob("*.log"))
    assert len(log_files) > 0
    
    # Verify configuration
    assert basic_config.log_level == "INFO"
"""
    
    def _generate_error_test_example(self) -> str:
        """Generate example error testing"""
        return """
def test_error_handling(storm_logger):
    \"\"\"Test error conditions and edge cases\"\"\"
    # Test with None parameters
    with pytest.raises(ValueError):
        storm_logger.log(None)
    
    # Test with invalid log level
    with pytest.raises(ValueError):
        storm_logger.log("Message", level="INVALID")
    
    # Test with extremely long message
    long_message = "x" * 10000
    result = storm_logger.log(long_message)
    assert len(result.message) <= 1000  # Should be truncated
    
    # Test with special characters
    special_message = "Test 🚀 with émojis and spëcial chars"
    result = storm_logger.log(special_message)
    assert result.status == "success"
"""
    
    def _generate_business_metrics_test_example(self) -> str:
        """Generate business metrics testing example"""
        return """
def test_business_metrics(storm_logger):
    \"\"\"Test business metrics collection and analysis\"\"\"
    # Track business events
    storm_logger.track_business_event("user_login", {"user_id": 123, "method": "oauth"})
    storm_logger.track_business_event("conversion", {"revenue": 99.99, "product": "premium"})
    
    # Verify metrics collection
    metrics = storm_logger.get_business_metrics()
    assert metrics["user_login_count"] == 1
    assert metrics["total_revenue"] == 99.99
    
    # Test business intelligence
    insights = storm_logger.generate_business_insights()
    assert "conversion_rate" in insights
    assert insights["conversion_rate"] > 0
"""
    
    def _generate_performance_test_example(self) -> str:
        """Generate performance testing example"""
        return """
def test_performance_requirements(storm_logger):
    \"\"\"Test Storm Logger performance requirements\"\"\"
    import time
    
    # Test high-volume logging (6M logs/sec capability)
    start_time = time.time()
    for i in range(1000):
        storm_logger.debug(f"Performance test {i}")
    duration = time.time() - start_time
    
    # Should handle 1000 logs very quickly
    assert duration < 0.1  # Less than 100ms for 1000 logs
    
    # Test with Daedalus C performance
    with storm_logger.performance_context("high_volume_test"):
        for i in range(10000):
            storm_logger.log(f"High volume test {i}")
    
    # Verify performance metrics
    perf_metrics = storm_logger.get_performance_metrics()
    assert perf_metrics["logs_per_second"] > 100000  # Should be very fast
"""
    
    def _generate_security_test_example(self) -> str:
        """Generate security testing example"""
        return """
def test_security_compliance(storm_logger):
    \"\"\"Test security and compliance features\"\"\"
    # Test PII sanitization
    pii_message = "User email: john.doe@example.com, SSN: 123-45-6789"
    result = storm_logger.log(pii_message)
    
    # PII should be sanitized
    assert "john.doe@example.com" not in result.sanitized_message
    assert "123-45-6789" not in result.sanitized_message
    assert "[EMAIL]" in result.sanitized_message
    assert "[SSN]" in result.sanitized_message
    
    # Test GDPR compliance
    gdpr_result = storm_logger.log("Personal data", gdpr_compliant=True)
    assert gdpr_result.compliance_flags["gdpr"] == True
    
    # Test HIPAA compliance
    hipaa_result = storm_logger.log("Medical record", hipaa_compliant=True)
    assert hipaa_result.compliance_flags["hipaa"] == True
"""
    
    def _generate_storm_assertion_example(self) -> str:
        """Generate Storm Logger specific assertion example"""
        return """
def test_with_storm_assertions(storm_logger):
    \"\"\"Test using Storm Logger specific assertions\"\"\"
    storm_logger.info("Test message with business context", user_id=123)
    
    # Use Storm Logger assertions
    assert_logs_contain(storm_logger, "Test message")
    assert_business_event_tracked(storm_logger, "log_created")
    assert_performance_metric(storm_logger, "log_duration", max_value=0.001)
    
    # Verify business intelligence
    assert_business_insight(storm_logger, "user_engagement", min_value=1)
"""
    
    def _generate_storm_context_example(self) -> str:
        """Generate Storm Logger context manager example"""
        return """
def test_with_storm_contexts(storm_logger):
    \"\"\"Test using Storm Logger context managers\"\"\"
    # Use performance context
    with storm_logger.performance_context("test_operation"):
        storm_logger.info("Operation started")
        # Simulate work
        time.sleep(0.001)
        storm_logger.info("Operation completed")
    
    # Use business context
    with storm_logger.business_context(user_id=123, session_id="abc123"):
        storm_logger.info("Business operation")
        storm_logger.track_business_event("user_action", {"action": "test"})
    
    # Use security context
    with storm_logger.security_context(compliance_level="high"):
        storm_logger.info("Sensitive operation", patient_id="[REDACTED]")
    
    # Verify contexts were applied
    metrics = storm_logger.get_context_metrics()
    assert metrics["performance_contexts"] == 1
    assert metrics["business_contexts"] == 1
    assert metrics["security_contexts"] == 1
"""


def analyze_test_file(test_file_path: str) -> str:
    """
    MCP function to analyze a test file and provide enhancement suggestions
    
    Args:
        test_file_path: Path to the test file to analyze
        
    Returns:
        JSON string with analysis results
    """
    enhancer = StormTestEnhancer()
    analysis = enhancer.analyze_test_file(test_file_path)
    
    return json.dumps(analysis.to_dict(), indent=2)


def enhance_test_quality(test_directory: str) -> str:
    """
    MCP function to enhance test quality across a directory
    
    Args:
        test_directory: Directory containing test files
        
    Returns:
        JSON string with enhancement recommendations
    """
    enhancer = StormTestEnhancer()
    test_dir = Path(test_directory)
    
    if not test_dir.exists():
        return json.dumps({"error": f"Directory {test_directory} does not exist"})
    
    analyses = []
    for test_file in test_dir.rglob("test_*.py"):
        analysis = enhancer.analyze_test_file(str(test_file))
        analyses.append(analysis)
    
    # Sort by priority score
    analyses.sort(key=lambda x: x.priority_score, reverse=True)
    
    # Generate summary
    summary = {
        "total_test_files": len(analyses),
        "high_priority_files": len([a for a in analyses if a.priority_score > 70]),
        "critical_issues": sum(len([s for s in a.suggestions if s.severity == "critical"]) for a in analyses),
        "total_suggestions": sum(len(a.suggestions) for a in analyses),
        "files_needing_attention": [
            {
                "file": a.test_file,
                "priority_score": a.priority_score,
                "coverage": a.coverage_percentage,
                "suggestions_count": len(a.suggestions),
                "business_impact": a.business_impact
            }
            for a in analyses[:10]  # Top 10 files
        ],
        "detailed_analyses": [a.to_dict() for a in analyses]
    }
    
    return json.dumps(summary, indent=2)


def generate_test_improvement_plan(test_file_path: str) -> str:
    """
    MCP function to generate a specific improvement plan for a test file
    
    Args:
        test_file_path: Path to the test file
        
    Returns:
        JSON string with improvement plan
    """
    enhancer = StormTestEnhancer()
    analysis = enhancer.analyze_test_file(test_file_path)
    
    # Group suggestions by type
    suggestions_by_type = {}
    for suggestion in analysis.suggestions:
        issue_type = suggestion.issue_type.value
        if issue_type not in suggestions_by_type:
            suggestions_by_type[issue_type] = []
        suggestions_by_type[issue_type].append(suggestion)
    
    # Generate improvement plan
    improvement_plan = {
        "file": test_file_path,
        "current_coverage": analysis.coverage_percentage,
        "target_coverage": 90.0,
        "priority_score": analysis.priority_score,
        "estimated_effort": analysis.enhancement_effort,
        "business_impact": analysis.business_impact,
        "improvement_phases": [
            {
                "phase": "Critical Issues",
                "priority": "immediate",
                "suggestions": [s.to_dict() for s in analysis.suggestions if s.severity == "critical"]
            },
            {
                "phase": "High Priority",
                "priority": "within_1_week",
                "suggestions": [s.to_dict() for s in analysis.suggestions if s.severity == "high"]
            },
            {
                "phase": "Medium Priority",
                "priority": "within_2_weeks",
                "suggestions": [s.to_dict() for s in analysis.suggestions if s.severity == "medium"]
            },
            {
                "phase": "Low Priority",
                "priority": "within_1_month",
                "suggestions": [s.to_dict() for s in analysis.suggestions if s.severity == "low"]
            }
        ],
        "suggestions_by_type": suggestions_by_type,
        "next_actions": [
            "Review critical issues first",
            "Implement suggested code examples",
            "Run tests to verify improvements",
            "Monitor coverage improvements"
        ]
    }
    
    return json.dumps(improvement_plan, indent=2)


# Legacy functions for backward compatibility
def enhance_script(current_options: List[str], workflow_pain_points: List[str], desired_features: List[str]) -> str:
    """
    Generate improvements for the Storm test script based on workflow analysis
    
    Args:
        current_options: Current script options (e.g., ["-k", "--quick", "--verbose"])
        workflow_pain_points: Issues identified in testing workflow
        desired_features: Requested new features
        
    Returns:
        JSON string with implementation suggestions and code snippets
    """
    enhancement = {
        "current_capabilities": current_options,
        "pain_points_analysis": [],
        "proposed_solutions": [],
        "implementation_priority": [],
        "code_snippets": {},
        "integration_strategy": []
    }
    
    # Analyze pain points and suggest solutions
    for pain_point in workflow_pain_points:
        pain_lower = pain_point.lower()
        
        if "slow" in pain_lower or "performance" in pain_lower:
            enhancement["pain_points_analysis"].append({
                "issue": "Test execution performance",
                "impact": "High - slows development iteration",
                "category": "Performance"
            })
            enhancement["proposed_solutions"].append({
                "solution": "Add test parallelization option",
                "implementation": "Add --parallel option using pytest-xdist",
                "effort": "Medium"
            })
            
        elif "filter" in pain_lower or "select" in pain_lower:
            enhancement["pain_points_analysis"].append({
                "issue": "Test selection and filtering",
                "impact": "Medium - hard to run specific tests",
                "category": "Usability"
            })
            enhancement["proposed_solutions"].append({
                "solution": "Enhanced filtering options",
                "implementation": "Add --tag, --module, --since options",
                "effort": "Low"
            })
            
        elif "output" in pain_lower or "format" in pain_lower:
            enhancement["pain_points_analysis"].append({
                "issue": "Test output formatting",
                "impact": "Low - readability issues", 
                "category": "User Experience"
            })
            enhancement["proposed_solutions"].append({
                "solution": "Improved output formatting",
                "implementation": "Add --minimal, --detailed output modes",
                "effort": "Low"
            })
    
    # Process desired features
    for feature in desired_features:
        feature_lower = feature.lower()
        
        if "watch" in feature_lower or "auto" in feature_lower:
            enhancement["proposed_solutions"].append({
                "solution": "File watching and auto-test execution",
                "implementation": "Use watchdog library for file monitoring",
                "effort": "High",
                "code_snippet": "file_watching"
            })
            
        elif "report" in feature_lower or "summary" in feature_lower:
            enhancement["proposed_solutions"].append({
                "solution": "Enhanced test reporting",
                "implementation": "Generate HTML reports and trend analysis", 
                "effort": "Medium",
                "code_snippet": "html_reporting"
            })
            
        elif "parallel" in feature_lower:
            enhancement["proposed_solutions"].append({
                "solution": "Parallel test execution",
                "implementation": "Integrate pytest-xdist for parallel runs",
                "effort": "Medium", 
                "code_snippet": "parallel_execution"
            })
    
    # Priority ranking
    high_impact = [s for s in enhancement["proposed_solutions"] if s.get("effort") == "Low"]
    medium_impact = [s for s in enhancement["proposed_solutions"] if s.get("effort") == "Medium"] 
    low_impact = [s for s in enhancement["proposed_solutions"] if s.get("effort") == "High"]
    
    enhancement["implementation_priority"] = [
        {"priority": "1 - Quick Wins", "solutions": high_impact},
        {"priority": "2 - Medium Effort", "solutions": medium_impact},
        {"priority": "3 - Long Term", "solutions": low_impact}
    ]
    
    # Code snippets for implementation
    enhancement["code_snippets"] = {
        "file_watching": '''
# Add to test.sh argument parsing:
--watch)
    WATCH_MODE=true
    shift
    ;;

# Add watch functionality:
if [ "$WATCH_MODE" = true ]; then
    echo "Storm Watch Mode: Monitoring for file changes..."
    watchmedo shell-command \\
        --patterns="*.py" \\
        --recursive \\
        --command="./test.sh $PYTEST_ARGS" \\
        .
fi''',
        
        "parallel_execution": '''
# Add to pytest args:
--parallel)
    PARALLEL_COUNT="${2:-auto}"
    PYTEST_ARGS="$PYTEST_ARGS -n $PARALLEL_COUNT"
    shift 2
    ;;''',
    
        "html_reporting": '''
# Add HTML report generation:
if [ "$GENERATE_HTML" = true ]; then
    PYTEST_ARGS="$PYTEST_ARGS --html=reports/storm_test_report.html --self-contained-html"
fi'''
    }
    
    # Integration strategy
    enhancement["integration_strategy"] = [
        "1. Implement low-effort improvements first for immediate value",
        "2. Add new options while maintaining backward compatibility",
        "3. Keep Storm branding and user experience consistent",
        "4. Test new features with existing test suite",
        "5. Update help documentation and examples",
        "6. Consider performance impact of new features"
    ]
    
    return json.dumps(enhancement, indent=2)