"""
Coverage Intelligence Tools for Storm Logger
Comprehensive coverage analysis and gap identification
"""

import json
import re
import subprocess
import sys
import time
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Any, Union


@dataclass
class CoverageModule:
    """Individual module coverage information"""
    name: str
    statements: int
    missing: int
    branches: int
    branch_partial: int
    coverage_percent: float
    missing_lines: List[str]
    priority: str
    complexity: str
    business_impact: str


@dataclass
class CoverageAnalysisResult:
    """Complete coverage analysis results"""
    overall_coverage: float
    total_statements: int
    total_missing: int
    target_coverage: float
    modules: List[CoverageModule]
    critical_gaps: List[str]
    quick_wins: List[str]
    recommendations: List[str]
    improvement_plan: Dict[str, Any]


class StormCoverageAnalyzer:
    """
    Comprehensive coverage analysis tool for Storm Logger
    Identifies gaps, prioritizes improvements, and provides actionable insights
    """
    
    def __init__(self, project_root: str = None):
        self.project_root = Path(project_root) if project_root else Path.cwd()
        self.storm_modules = self._identify_storm_modules()
        
        # Business impact classifications
        self.business_impact_map = {
            'business_metrics': 'CRITICAL',
            'sanitizer': 'CRITICAL', 
            'sanitizer_v2': 'CRITICAL',
            'professional_logger': 'HIGH',
            'message_formatter': 'HIGH',
            'storm_console': 'HIGH',
            'context_detector': 'MEDIUM',
            'django_config': 'MEDIUM',
            'standalone': 'LOW',
            'patterns': 'MEDIUM',
        }
        
        # Complexity classifications
        self.complexity_map = {
            'business_metrics': 'HIGH',
            'sanitizer': 'HIGH',
            'message_formatter': 'HIGH',
            'professional_logger': 'MEDIUM',
            'storm_console': 'MEDIUM',
            'context_detector': 'MEDIUM',
            'django_config': 'MEDIUM',
            'standalone': 'LOW',
            'patterns': 'MEDIUM',
        }
    
    def _identify_storm_modules(self) -> List[str]:
        """Identify all Storm Logger modules for analysis"""
        storm_dir = self.project_root / 'storm_logger'
        if not storm_dir.exists():
            return []
        
        modules = []
        
        # Find all Python files in storm_logger
        for py_file in storm_dir.rglob('*.py'):
            if py_file.name != '__init__.py':
                # Convert to module path
                rel_path = py_file.relative_to(storm_dir.parent)
                module_name = str(rel_path.with_suffix('')).replace('/', '.')
                modules.append(module_name)
        
        return modules
    
    def _run_coverage_analysis(self, target_modules: List[str] = None) -> Dict[str, Any]:
        """Run coverage analysis and parse results"""
        try:
            # Build coverage command
            cmd = [
                sys.executable, '-m', 'pytest',
                '--cov=storm_logger',
                '--cov-report=term-missing',
                '--cov-report=json',
                '--tb=no',
                '-q'
            ]
            
            if target_modules:
                cmd.extend(target_modules)
            
            # Run coverage
            result = subprocess.run(
                cmd,
                cwd=self.project_root,
                capture_output=True,
                text=True,
                timeout=300
            )
            
            # Parse JSON coverage report
            coverage_json_path = self.project_root / 'coverage.json'
            if coverage_json_path.exists():
                with open(coverage_json_path, 'r') as f:
                    coverage_data = json.load(f)
                return coverage_data
            
            # Fallback to parsing text output
            return self._parse_coverage_text(result.stdout)
            
        except subprocess.TimeoutExpired:
            return {'error': 'Coverage analysis timed out'}
        except Exception as e:
            return {'error': f'Coverage analysis failed: {str(e)}'}
    
    def _parse_coverage_text(self, coverage_output: str) -> Dict[str, Any]:
        """Parse coverage text output as fallback"""
        modules = {}
        
        # Parse each line looking for coverage data
        lines = coverage_output.split('\n')
        for line in lines:
            if 'storm_logger' in line and '%' in line:
                parts = line.split()
                if len(parts) >= 6:
                    module_name = parts[0]
                    try:
                        statements = int(parts[1])
                        missing = int(parts[2])
                        coverage = float(parts[-1].replace('%', ''))
                        
                        modules[module_name] = {
                            'summary': {
                                'num_statements': statements,
                                'missing_lines': missing,
                                'coverage': coverage,
                                'excluded_lines': 0,
                                'num_branches': 0,
                                'num_partial_branches': 0
                            },
                            'missing_lines': []
                        }
                    except (ValueError, IndexError):
                        continue
        
        return {
            'files': modules,
            'totals': {
                'num_statements': sum(m['summary']['num_statements'] for m in modules.values()),
                'missing_lines': sum(m['summary']['missing_lines'] for m in modules.values()),
                'coverage': 0.0  # Will be calculated
            }
        }
    
    def _classify_module_priority(self, module_name: str, coverage_percent: float) -> str:
        """Classify module priority based on business impact and coverage"""
        # Extract base module name for classification
        base_name = module_name.split('.')[-1]
        
        business_impact = self.business_impact_map.get(base_name, 'LOW')
        
        if coverage_percent < 50:
            if business_impact == 'CRITICAL':
                return 'CRITICAL'
            elif business_impact == 'HIGH':
                return 'HIGH'
            else:
                return 'MEDIUM'
        elif coverage_percent < 75:
            if business_impact == 'CRITICAL':
                return 'HIGH'
            else:
                return 'MEDIUM'
        else:
            return 'LOW'
    
    def _get_module_complexity(self, module_name: str) -> str:
        """Get module complexity classification"""
        base_name = module_name.split('.')[-1]
        return self.complexity_map.get(base_name, 'MEDIUM')
    
    def _get_business_impact(self, module_name: str) -> str:
        """Get business impact classification"""
        base_name = module_name.split('.')[-1]
        return self.business_impact_map.get(base_name, 'LOW')
    
    def _generate_improvement_plan(self, modules: List[CoverageModule]) -> Dict[str, Any]:
        """Generate comprehensive improvement plan"""
        plan = {
            'phases': [],
            'estimated_effort': {},
            'quick_wins': [],
            'long_term_goals': [],
            'resource_requirements': {}
        }
        
        # Sort modules by priority and impact
        critical_modules = [m for m in modules if m.priority == 'CRITICAL']
        high_priority = [m for m in modules if m.priority == 'HIGH']
        medium_priority = [m for m in modules if m.priority == 'MEDIUM']
        
        # Phase 1: Critical modules
        if critical_modules:
            plan['phases'].append({
                'phase': 1,
                'title': 'Critical Business Logic Coverage',
                'modules': [m.name for m in critical_modules],
                'target_coverage': 95,
                'estimated_days': len(critical_modules) * 2,
                'priority': 'CRITICAL'
            })
        
        # Phase 2: High priority modules
        if high_priority:
            plan['phases'].append({
                'phase': 2,
                'title': 'Core Functionality Coverage',
                'modules': [m.name for m in high_priority],
                'target_coverage': 90,
                'estimated_days': len(high_priority) * 1.5,
                'priority': 'HIGH'
            })
        
        # Phase 3: Medium priority modules
        if medium_priority:
            plan['phases'].append({
                'phase': 3,
                'title': 'Supporting Systems Coverage',
                'modules': [m.name for m in medium_priority],
                'target_coverage': 85,
                'estimated_days': len(medium_priority) * 1,
                'priority': 'MEDIUM'
            })
        
        # Identify quick wins (low complexity, high impact)
        quick_wins = [
            m for m in modules 
            if m.complexity == 'LOW' and m.business_impact in ['HIGH', 'CRITICAL']
            and m.coverage_percent < 80
        ]
        plan['quick_wins'] = [m.name for m in quick_wins]
        
        # Estimate effort
        plan['estimated_effort'] = {
            'total_days': sum(phase['estimated_days'] for phase in plan['phases']),
            'total_tests': sum(max(1, m.missing // 10) for m in modules if m.priority in ['CRITICAL', 'HIGH']),
            'complexity_breakdown': {
                'LOW': len([m for m in modules if m.complexity == 'LOW']),
                'MEDIUM': len([m for m in modules if m.complexity == 'MEDIUM']),
                'HIGH': len([m for m in modules if m.complexity == 'HIGH'])
            }
        }
        
        return plan
    
    def analyze_coverage_gaps(self, run_coverage: bool = True) -> str:
        """
        Comprehensive coverage gap analysis
        
        Args:
            run_coverage: Whether to run coverage analysis or use existing data
            
        Returns:
            JSON string with detailed coverage analysis
        """
        try:
            # Get coverage data
            if run_coverage:
                coverage_data = self._run_coverage_analysis()
            else:
                # Try to load existing coverage data
                coverage_json_path = self.project_root / 'coverage.json'
                if coverage_json_path.exists():
                    with open(coverage_json_path, 'r') as f:
                        coverage_data = json.load(f)
                else:
                    coverage_data = self._run_coverage_analysis()
            
            if 'error' in coverage_data:
                return json.dumps({
                    'status': 'error',
                    'message': coverage_data['error'],
                    'timestamp': time.time()
                })
            
            # Parse coverage data
            modules = []
            
            for file_path, file_data in coverage_data.get('files', {}).items():
                if 'storm_logger' in file_path:
                    summary = file_data.get('summary', {})
                    
                    module = CoverageModule(
                        name=file_path,
                        statements=summary.get('num_statements', 0),
                        missing=summary.get('missing_lines', 0),
                        branches=summary.get('num_branches', 0),
                        branch_partial=summary.get('num_partial_branches', 0),
                        coverage_percent=summary.get('coverage', 0.0),
                        missing_lines=file_data.get('missing_lines', []),
                        priority=self._classify_module_priority(file_path, summary.get('coverage', 0.0)),
                        complexity=self._get_module_complexity(file_path),
                        business_impact=self._get_business_impact(file_path)
                    )
                    modules.append(module)
            
            # Calculate overall metrics
            total_statements = sum(m.statements for m in modules)
            total_missing = sum(m.missing for m in modules)
            overall_coverage = ((total_statements - total_missing) / total_statements * 100) if total_statements > 0 else 0
            
            # Identify critical gaps
            critical_gaps = [
                m.name for m in modules 
                if m.priority == 'CRITICAL' and m.coverage_percent < 50
            ]
            
            # Identify quick wins
            quick_wins = [
                m.name for m in modules 
                if m.complexity == 'LOW' and m.coverage_percent < 80
            ]
            
            # Generate recommendations
            recommendations = self._generate_recommendations(modules, overall_coverage)
            
            # Create improvement plan
            improvement_plan = self._generate_improvement_plan(modules)
            
            # Build analysis result
            analysis = CoverageAnalysisResult(
                overall_coverage=overall_coverage,
                total_statements=total_statements,
                total_missing=total_missing,
                target_coverage=90.0,
                modules=modules,
                critical_gaps=critical_gaps,
                quick_wins=quick_wins,
                recommendations=recommendations,
                improvement_plan=improvement_plan
            )
            
            return json.dumps({
                'status': 'success',
                'analysis': asdict(analysis),
                'timestamp': time.time(),
                'summary': {
                    'current_coverage': f"{overall_coverage:.1f}%",
                    'target_coverage': "90.0%",
                    'gap': f"{90.0 - overall_coverage:.1f}%",
                    'modules_analyzed': len(modules),
                    'critical_gaps': len(critical_gaps),
                    'quick_wins': len(quick_wins),
                    'estimated_effort': improvement_plan['estimated_effort']['total_days']
                }
            }, indent=2)
            
        except Exception as e:
            return json.dumps({
                'status': 'error',
                'message': f'Coverage analysis failed: {str(e)}',
                'timestamp': time.time()
            })
    
    def _generate_recommendations(self, modules: List[CoverageModule], overall_coverage: float) -> List[str]:
        """Generate actionable recommendations"""
        recommendations = []
        
        # Overall coverage recommendations
        if overall_coverage < 50:
            recommendations.append("🚨 CRITICAL: Overall coverage is severely low. Focus on business-critical modules first.")
        elif overall_coverage < 75:
            recommendations.append("⚠️ HIGH PRIORITY: Coverage is below acceptable levels. Implement systematic testing strategy.")
        elif overall_coverage < 90:
            recommendations.append("📈 MEDIUM PRIORITY: Good progress! Focus on remaining gaps to reach 90% target.")
        
        # Module-specific recommendations
        critical_modules = [m for m in modules if m.priority == 'CRITICAL']
        if critical_modules:
            recommendations.append(f"🎯 Focus on {len(critical_modules)} critical modules: {', '.join(m.name.split('.')[-1] for m in critical_modules[:3])}")
        
        # Quick wins
        quick_wins = [m for m in modules if m.complexity == 'LOW' and m.coverage_percent < 80]
        if quick_wins:
            recommendations.append(f"⚡ {len(quick_wins)} quick wins available for immediate improvement")
        
        # Business impact recommendations
        business_critical = [m for m in modules if m.business_impact == 'CRITICAL' and m.coverage_percent < 80]
        if business_critical:
            recommendations.append(f"💼 Business-critical modules need attention: {', '.join(m.name.split('.')[-1] for m in business_critical)}")
        
        # Technical recommendations
        high_complexity = [m for m in modules if m.complexity == 'HIGH' and m.coverage_percent < 70]
        if high_complexity:
            recommendations.append(f"🔧 Complex modules requiring careful testing: {', '.join(m.name.split('.')[-1] for m in high_complexity)}")
        
        return recommendations
    
    def prioritize_coverage_improvements(self, focus_area: str = "business_impact") -> str:
        """
        Prioritize coverage improvements based on different criteria
        
        Args:
            focus_area: "business_impact", "complexity", "coverage_gap", "quick_wins"
            
        Returns:
            JSON string with prioritized improvement plan
        """
        try:
            # Get current coverage analysis
            analysis_result = json.loads(self.analyze_coverage_gaps(run_coverage=False))
            
            if analysis_result['status'] != 'success':
                return json.dumps(analysis_result)
            
            modules = analysis_result['analysis']['modules']
            
            # Sort modules based on focus area
            if focus_area == "business_impact":
                priority_order = {'CRITICAL': 4, 'HIGH': 3, 'MEDIUM': 2, 'LOW': 1}
                sorted_modules = sorted(modules, key=lambda m: (
                    priority_order.get(m['business_impact'], 0),
                    100 - m['coverage_percent']
                ), reverse=True)
            elif focus_area == "complexity":
                complexity_order = {'LOW': 3, 'MEDIUM': 2, 'HIGH': 1}
                sorted_modules = sorted(modules, key=lambda m: (
                    complexity_order.get(m['complexity'], 0),
                    100 - m['coverage_percent']
                ), reverse=True)
            elif focus_area == "coverage_gap":
                sorted_modules = sorted(modules, key=lambda m: m['coverage_percent'])
            elif focus_area == "quick_wins":
                sorted_modules = sorted(modules, key=lambda m: (
                    m['complexity'] == 'LOW',
                    m['business_impact'] in ['HIGH', 'CRITICAL'],
                    100 - m['coverage_percent']
                ), reverse=True)
            else:
                sorted_modules = modules
            
            # Generate prioritized plan
            plan = {
                'focus_area': focus_area,
                'prioritized_modules': sorted_modules[:10],  # Top 10
                'implementation_phases': [],
                'expected_outcomes': {},
                'resource_allocation': {}
            }
            
            # Create implementation phases
            for i, module in enumerate(sorted_modules[:6]):  # Top 6 modules
                phase = {
                    'phase': i + 1,
                    'module': module['name'],
                    'current_coverage': module['coverage_percent'],
                    'target_coverage': 90 if module['business_impact'] == 'CRITICAL' else 85,
                    'estimated_effort': self._estimate_effort(module),
                    'priority': module['priority'],
                    'complexity': module['complexity'],
                    'business_impact': module['business_impact']
                }
                plan['implementation_phases'].append(phase)
            
            # Calculate expected outcomes
            total_statements = sum(m['statements'] for m in sorted_modules[:6])
            total_missing = sum(m['missing'] for m in sorted_modules[:6])
            potential_improvement = (total_missing * 0.8) / total_statements * 100  # Assume 80% of missing covered
            
            plan['expected_outcomes'] = {
                'coverage_improvement': f"{potential_improvement:.1f}%",
                'modules_improved': len(plan['implementation_phases']),
                'estimated_timeline': f"{sum(phase['estimated_effort'] for phase in plan['implementation_phases'])} days",
                'business_value': self._calculate_business_value(sorted_modules[:6])
            }
            
            return json.dumps({
                'status': 'success',
                'prioritization_plan': plan,
                'timestamp': time.time()
            }, indent=2)
            
        except Exception as e:
            return json.dumps({
                'status': 'error',
                'message': f'Prioritization failed: {str(e)}',
                'timestamp': time.time()
            })
    
    def _estimate_effort(self, module: Dict[str, Any]) -> int:
        """Estimate effort in days for improving module coverage"""
        base_effort = 1  # Base 1 day
        
        # Adjust for complexity
        if module['complexity'] == 'HIGH':
            base_effort *= 2
        elif module['complexity'] == 'MEDIUM':
            base_effort *= 1.5
        
        # Adjust for missing coverage
        coverage_gap = 100 - module['coverage_percent']
        if coverage_gap > 50:
            base_effort *= 1.5
        
        # Adjust for module size
        if module['statements'] > 200:
            base_effort *= 1.3
        
        return max(1, int(base_effort))
    
    def _calculate_business_value(self, modules: List[Dict[str, Any]]) -> str:
        """Calculate business value of coverage improvements"""
        critical_count = sum(1 for m in modules if m['business_impact'] == 'CRITICAL')
        high_count = sum(1 for m in modules if m['business_impact'] == 'HIGH')
        
        if critical_count > 0:
            return "HIGH - Critical business logic protected"
        elif high_count > 0:
            return "MEDIUM - Important functionality secured"
        else:
            return "LOW - Supporting systems improved"
    
    def generate_coverage_strategy(self, team_size: str = "small", timeline: str = "4_weeks") -> str:
        """
        Generate comprehensive coverage improvement strategy
        
        Args:
            team_size: "small" (1-2 devs), "medium" (3-5 devs), "large" (6+ devs)
            timeline: "2_weeks", "4_weeks", "8_weeks", "12_weeks"
            
        Returns:
            JSON string with detailed strategy
        """
        try:
            # Get current analysis
            analysis_result = json.loads(self.analyze_coverage_gaps(run_coverage=False))
            
            if analysis_result['status'] != 'success':
                return json.dumps(analysis_result)
            
            # Team capacity mapping
            team_capacity = {
                'small': {'daily_capacity': 2, 'parallel_work': 1},
                'medium': {'daily_capacity': 6, 'parallel_work': 2},
                'large': {'daily_capacity': 12, 'parallel_work': 3}
            }
            
            # Timeline mapping (in days)
            timeline_days = {
                '2_weeks': 10,
                '4_weeks': 20,
                '8_weeks': 40,
                '12_weeks': 60
            }
            
            capacity = team_capacity.get(team_size, team_capacity['small'])
            available_days = timeline_days.get(timeline, 20)
            total_capacity = capacity['daily_capacity'] * available_days
            
            analysis = analysis_result['analysis']
            modules = analysis['modules']
            
            # Filter modules that need improvement
            improvement_modules = [m for m in modules if m['coverage_percent'] < 85]
            
            # Sort by priority and select feasible modules
            priority_order = {'CRITICAL': 4, 'HIGH': 3, 'MEDIUM': 2, 'LOW': 1}
            sorted_modules = sorted(improvement_modules, key=lambda m: (
                priority_order.get(m['priority'], 0),
                100 - m['coverage_percent']
            ), reverse=True)
            
            # Select modules that fit within capacity
            selected_modules = []
            used_capacity = 0
            
            for module in sorted_modules:
                effort = self._estimate_effort(module)
                if used_capacity + effort <= total_capacity:
                    selected_modules.append(module)
                    used_capacity += effort
            
            # Generate strategy
            strategy = {
                'team_configuration': {
                    'size': team_size,
                    'timeline': timeline,
                    'total_capacity': total_capacity,
                    'parallel_work_streams': capacity['parallel_work']
                },
                'coverage_goals': {
                    'current_coverage': analysis['overall_coverage'],
                    'target_coverage': 90.0,
                    'modules_to_improve': len(selected_modules),
                    'estimated_final_coverage': self._estimate_final_coverage(analysis, selected_modules)
                },
                'work_phases': self._generate_work_phases(selected_modules, capacity['parallel_work']),
                'resource_allocation': {
                    'testing_focus': f"{len([m for m in selected_modules if m['priority'] == 'CRITICAL'])} critical modules",
                    'quick_wins': f"{len([m for m in selected_modules if m['complexity'] == 'LOW'])} low-complexity modules",
                    'capacity_utilization': f"{used_capacity}/{total_capacity} days ({used_capacity/total_capacity*100:.1f}%)"
                },
                'success_metrics': {
                    'coverage_improvement': f"{self._estimate_final_coverage(analysis, selected_modules) - analysis['overall_coverage']:.1f}%",
                    'modules_completed': len(selected_modules),
                    'business_value': self._calculate_business_value(selected_modules)
                },
                'recommendations': self._generate_strategy_recommendations(selected_modules, team_size, timeline)
            }
            
            return json.dumps({
                'status': 'success',
                'strategy': strategy,
                'timestamp': time.time()
            }, indent=2)
            
        except Exception as e:
            return json.dumps({
                'status': 'error',
                'message': f'Strategy generation failed: {str(e)}',
                'timestamp': time.time()
            })
    
    def _estimate_final_coverage(self, analysis: Dict[str, Any], selected_modules: List[Dict[str, Any]]) -> float:
        """Estimate final coverage after improvements"""
        current_coverage = analysis['overall_coverage']
        total_statements = analysis['total_statements']
        
        # Estimate additional coverage from selected modules
        additional_coverage = 0
        for module in selected_modules:
            # Assume we'll cover 80% of missing statements
            additional_statements = module['missing'] * 0.8
            additional_coverage += additional_statements / total_statements * 100
        
        return min(95.0, current_coverage + additional_coverage)
    
    def _generate_work_phases(self, modules: List[Dict[str, Any]], parallel_streams: int) -> List[Dict[str, Any]]:
        """Generate work phases for parallel execution"""
        phases = []
        
        # Group modules by priority
        critical_modules = [m for m in modules if m['priority'] == 'CRITICAL']
        high_modules = [m for m in modules if m['priority'] == 'HIGH']
        medium_modules = [m for m in modules if m['priority'] == 'MEDIUM']
        
        phase_num = 1
        
        # Phase 1: Critical modules (highest priority)
        if critical_modules:
            phases.append({
                'phase': phase_num,
                'title': 'Critical Business Logic',
                'modules': critical_modules,
                'parallel_streams': min(parallel_streams, len(critical_modules)),
                'estimated_duration': max(self._estimate_effort(m) for m in critical_modules),
                'success_criteria': 'All critical modules reach 90%+ coverage'
            })
            phase_num += 1
        
        # Phase 2: High priority modules
        if high_modules:
            phases.append({
                'phase': phase_num,
                'title': 'Core Functionality',
                'modules': high_modules,
                'parallel_streams': min(parallel_streams, len(high_modules)),
                'estimated_duration': max(self._estimate_effort(m) for m in high_modules),
                'success_criteria': 'High priority modules reach 85%+ coverage'
            })
            phase_num += 1
        
        # Phase 3: Medium priority modules
        if medium_modules:
            phases.append({
                'phase': phase_num,
                'title': 'Supporting Systems',
                'modules': medium_modules,
                'parallel_streams': min(parallel_streams, len(medium_modules)),
                'estimated_duration': max(self._estimate_effort(m) for m in medium_modules),
                'success_criteria': 'Medium priority modules reach 80%+ coverage'
            })
        
        return phases
    
    def _generate_strategy_recommendations(self, modules: List[Dict[str, Any]], team_size: str, timeline: str) -> List[str]:
        """Generate strategy-specific recommendations"""
        recommendations = []
        
        if team_size == 'small':
            recommendations.append("👥 Small team: Focus on one module at a time for maximum efficiency")
            recommendations.append("⚡ Prioritize quick wins to build momentum")
        elif team_size == 'medium':
            recommendations.append("👥 Medium team: Split into 2 parallel workstreams")
            recommendations.append("🔄 Pair experienced developers with junior team members")
        else:
            recommendations.append("👥 Large team: Implement 3 parallel workstreams with clear ownership")
            recommendations.append("📊 Use code review process to maintain quality")
        
        if timeline == '2_weeks':
            recommendations.append("⏰ Short timeline: Focus only on critical modules")
            recommendations.append("🎯 Aim for 80% coverage on selected modules")
        elif timeline == '4_weeks':
            recommendations.append("⏰ Standard timeline: Balance critical and high-priority modules")
            recommendations.append("🎯 Aim for 85% coverage on selected modules")
        else:
            recommendations.append("⏰ Extended timeline: Comprehensive coverage improvement")
            recommendations.append("🎯 Aim for 90% coverage on all selected modules")
        
        # Module-specific recommendations
        critical_count = len([m for m in modules if m['priority'] == 'CRITICAL'])
        if critical_count > 0:
            recommendations.append(f"🚨 {critical_count} critical modules identified - highest priority")
        
        complex_count = len([m for m in modules if m['complexity'] == 'HIGH'])
        if complex_count > 0:
            recommendations.append(f"🔧 {complex_count} complex modules - allocate senior developers")
        
        return recommendations


def analyze_coverage_gaps(
    project_path: str,
    run_coverage: bool = True,
    focus_modules: List[str] = None
) -> str:
    """
    Analyze coverage gaps for Storm Logger project
    
    Args:
        project_path: Path to the Storm Logger project
        run_coverage: Whether to run coverage analysis
        focus_modules: Specific modules to focus on
        
    Returns:
        JSON string with comprehensive coverage analysis
    """
    analyzer = StormCoverageAnalyzer(project_path)
    return analyzer.analyze_coverage_gaps(run_coverage)


def prioritize_coverage_improvements(
    project_path: str,
    focus_area: str = "business_impact"
) -> str:
    """
    Prioritize coverage improvements based on business impact
    
    Args:
        project_path: Path to the Storm Logger project
        focus_area: Focus area for prioritization
        
    Returns:
        JSON string with prioritized improvement plan
    """
    analyzer = StormCoverageAnalyzer(project_path)
    return analyzer.prioritize_coverage_improvements(focus_area)


def generate_coverage_strategy(
    project_path: str,
    team_size: str = "small",
    timeline: str = "4_weeks"
) -> str:
    """
    Generate comprehensive coverage improvement strategy
    
    Args:
        project_path: Path to the Storm Logger project
        team_size: Team size for resource planning
        timeline: Timeline for implementation
        
    Returns:
        JSON string with detailed strategy
    """
    analyzer = StormCoverageAnalyzer(project_path)
    return analyzer.generate_coverage_strategy(team_size, timeline)