"""
Storm Logger Coverage Reporting and Tracking System
Provides comprehensive coverage tracking, reporting, and trend analysis
"""

import json
import datetime
import sqlite3
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, CoverageAnalysisResult
from .test_enhancement import StormTestEnhancer


class ReportType(Enum):
    """Types of coverage reports"""
    SUMMARY = "summary"
    DETAILED = "detailed"
    TREND = "trend"
    BUSINESS_IMPACT = "business_impact"
    PRIORITIZED = "prioritized"


@dataclass
class CoverageMetrics:
    """Coverage metrics for tracking"""
    timestamp: str
    overall_coverage: float
    critical_module_coverage: float
    test_count: int
    missing_tests: int
    business_critical_gaps: int
    performance_critical_gaps: int
    security_critical_gaps: int
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary"""
        return asdict(self)


@dataclass
class CoverageTrend:
    """Coverage trend analysis"""
    period: str
    metrics: List[CoverageMetrics]
    improvement_rate: float
    regression_count: int
    target_progress: float
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary"""
        return asdict(self)


@dataclass
class CoverageReport:
    """Comprehensive coverage report"""
    report_type: ReportType
    generated_at: str
    summary: Dict[str, Any]
    detailed_analysis: Optional[CoverageAnalysisResult] = None
    trend_analysis: Optional[CoverageTrend] = None
    recommendations: List[str] = None
    priority_actions: List[str] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary"""
        return asdict(self)


class StormCoverageTracker:
    """
    Storm Logger Coverage Tracking System
    Tracks coverage metrics over time and provides trend analysis
    """
    
    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)
        self.test_enhancer = StormTestEnhancer(project_root)
        self.db_path = self.project_root / "reports" / "coverage_tracking.db"
        self._ensure_db_exists()
        
        # Storm Logger business targets
        self.business_targets = {
            'overall_coverage': 90.0,
            'critical_module_coverage': 95.0,
            'business_critical_coverage': 100.0,
            'performance_critical_coverage': 95.0,
            'security_critical_coverage': 100.0
        }
        
        # Business-critical modules for Storm Logger $50M empire
        self.business_critical_modules = [
            'business_metrics',
            'professional_logger', 
            'django',
            'sanitizer',
            'patterns'
        ]
    
    def _ensure_db_exists(self):
        """Ensure tracking database exists"""
        self.db_path.parent.mkdir(parents=True, exist_ok=True)
        
        conn = sqlite3.connect(str(self.db_path))
        cursor = conn.cursor()
        
        # Create coverage metrics table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS coverage_metrics (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT NOT NULL,
                overall_coverage REAL NOT NULL,
                critical_module_coverage REAL NOT NULL,
                test_count INTEGER NOT NULL,
                missing_tests INTEGER NOT NULL,
                business_critical_gaps INTEGER NOT NULL,
                performance_critical_gaps INTEGER NOT NULL,
                security_critical_gaps INTEGER NOT NULL,
                raw_data TEXT NOT NULL
            )
        ''')
        
        # Create test tracking table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS test_tracking (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT NOT NULL,
                test_file TEXT NOT NULL,
                coverage_percentage REAL NOT NULL,
                suggestions_count INTEGER NOT NULL,
                priority_score INTEGER NOT NULL,
                enhancement_effort TEXT NOT NULL,
                business_impact TEXT NOT NULL
            )
        ''')
        
        conn.commit()
        conn.close()
    
    def record_coverage_snapshot(self) -> CoverageMetrics:
        """Record current coverage snapshot"""
        timestamp = datetime.datetime.now().isoformat()
        
        # Get current coverage analysis
        coverage_analysis = self.coverage_analyzer.analyze_coverage_gaps()
        
        # Calculate metrics
        overall_coverage = coverage_analysis.overall_coverage
        critical_modules = [m for m in coverage_analysis.modules 
                          if any(crit in m.file_path.lower() for crit in self.business_critical_modules)]
        
        critical_module_coverage = sum(m.coverage_percentage for m in critical_modules) / len(critical_modules) if critical_modules else 0.0
        
        # Count gaps
        business_critical_gaps = len([m for m in critical_modules if m.coverage_percentage < self.business_targets['business_critical_coverage']])
        performance_critical_gaps = len([m for m in coverage_analysis.modules if 'performance' in m.file_path.lower() and m.coverage_percentage < self.business_targets['performance_critical_coverage']])
        security_critical_gaps = len([m for m in coverage_analysis.modules if any(sec in m.file_path.lower() for sec in ['sanitizer', 'security', 'patterns']) and m.coverage_percentage < self.business_targets['security_critical_coverage']])
        
        metrics = CoverageMetrics(
            timestamp=timestamp,
            overall_coverage=overall_coverage,
            critical_module_coverage=critical_module_coverage,
            test_count=len(coverage_analysis.modules),
            missing_tests=len([m for m in coverage_analysis.modules if m.coverage_percentage < 90.0]),
            business_critical_gaps=business_critical_gaps,
            performance_critical_gaps=performance_critical_gaps,
            security_critical_gaps=security_critical_gaps
        )
        
        # Store in database
        self._store_metrics(metrics, coverage_analysis)
        
        return metrics
    
    def _store_metrics(self, metrics: CoverageMetrics, coverage_analysis: CoverageAnalysisResult):
        """Store metrics in database"""
        conn = sqlite3.connect(str(self.db_path))
        cursor = conn.cursor()
        
        cursor.execute('''
            INSERT INTO coverage_metrics 
            (timestamp, overall_coverage, critical_module_coverage, test_count, 
             missing_tests, business_critical_gaps, performance_critical_gaps, 
             security_critical_gaps, raw_data)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ''', (
            metrics.timestamp,
            metrics.overall_coverage,
            metrics.critical_module_coverage,
            metrics.test_count,
            metrics.missing_tests,
            metrics.business_critical_gaps,
            metrics.performance_critical_gaps,
            metrics.security_critical_gaps,
            json.dumps(coverage_analysis.to_dict())
        ))
        
        conn.commit()
        conn.close()
    
    def get_coverage_trend(self, days: int = 30) -> CoverageTrend:
        """Get coverage trend over specified period"""
        conn = sqlite3.connect(str(self.db_path))
        cursor = conn.cursor()
        
        # Get metrics from last N days
        cutoff_date = (datetime.datetime.now() - datetime.timedelta(days=days)).isoformat()
        
        cursor.execute('''
            SELECT timestamp, overall_coverage, critical_module_coverage, test_count,
                   missing_tests, business_critical_gaps, performance_critical_gaps,
                   security_critical_gaps
            FROM coverage_metrics
            WHERE timestamp > ?
            ORDER BY timestamp
        ''', (cutoff_date,))
        
        rows = cursor.fetchall()
        conn.close()
        
        if not rows:
            return CoverageTrend(
                period=f"last_{days}_days",
                metrics=[],
                improvement_rate=0.0,
                regression_count=0,
                target_progress=0.0
            )
        
        # Convert to CoverageMetrics
        metrics = []
        for row in rows:
            metrics.append(CoverageMetrics(
                timestamp=row[0],
                overall_coverage=row[1],
                critical_module_coverage=row[2],
                test_count=row[3],
                missing_tests=row[4],
                business_critical_gaps=row[5],
                performance_critical_gaps=row[6],
                security_critical_gaps=row[7]
            ))
        
        # Calculate improvement rate
        if len(metrics) >= 2:
            start_coverage = metrics[0].overall_coverage
            end_coverage = metrics[-1].overall_coverage
            improvement_rate = ((end_coverage - start_coverage) / start_coverage) * 100 if start_coverage > 0 else 0.0
        else:
            improvement_rate = 0.0
        
        # Count regressions
        regression_count = 0
        for i in range(1, len(metrics)):
            if metrics[i].overall_coverage < metrics[i-1].overall_coverage:
                regression_count += 1
        
        # Calculate target progress
        current_coverage = metrics[-1].overall_coverage if metrics else 0.0
        target_coverage = self.business_targets['overall_coverage']
        target_progress = (current_coverage / target_coverage) * 100 if target_coverage > 0 else 0.0
        
        return CoverageTrend(
            period=f"last_{days}_days",
            metrics=metrics,
            improvement_rate=improvement_rate,
            regression_count=regression_count,
            target_progress=target_progress
        )
    
    def generate_coverage_report(self, report_type: ReportType = ReportType.SUMMARY) -> CoverageReport:
        """Generate comprehensive coverage report"""
        timestamp = datetime.datetime.now().isoformat()
        
        if report_type == ReportType.SUMMARY:
            return self._generate_summary_report(timestamp)
        elif report_type == ReportType.DETAILED:
            return self._generate_detailed_report(timestamp)
        elif report_type == ReportType.TREND:
            return self._generate_trend_report(timestamp)
        elif report_type == ReportType.BUSINESS_IMPACT:
            return self._generate_business_impact_report(timestamp)
        elif report_type == ReportType.PRIORITIZED:
            return self._generate_prioritized_report(timestamp)
        else:
            return self._generate_summary_report(timestamp)
    
    def _generate_summary_report(self, timestamp: str) -> CoverageReport:
        """Generate summary coverage report"""
        current_metrics = self.record_coverage_snapshot()
        coverage_analysis = self.coverage_analyzer.analyze_coverage_gaps()
        
        summary = {
            "current_coverage": current_metrics.overall_coverage,
            "target_coverage": self.business_targets['overall_coverage'],
            "gap_to_target": self.business_targets['overall_coverage'] - current_metrics.overall_coverage,
            "critical_module_coverage": current_metrics.critical_module_coverage,
            "business_critical_gaps": current_metrics.business_critical_gaps,
            "performance_critical_gaps": current_metrics.performance_critical_gaps,
            "security_critical_gaps": current_metrics.security_critical_gaps,
            "total_modules": current_metrics.test_count,
            "modules_needing_improvement": current_metrics.missing_tests,
            "business_impact": self._assess_business_impact(current_metrics),
            "priority_modules": self._get_priority_modules(coverage_analysis)
        }
        
        recommendations = self._generate_recommendations(current_metrics, coverage_analysis)
        priority_actions = self._generate_priority_actions(current_metrics, coverage_analysis)
        
        return CoverageReport(
            report_type=ReportType.SUMMARY,
            generated_at=timestamp,
            summary=summary,
            recommendations=recommendations,
            priority_actions=priority_actions
        )
    
    def _generate_detailed_report(self, timestamp: str) -> CoverageReport:
        """Generate detailed coverage report"""
        current_metrics = self.record_coverage_snapshot()
        coverage_analysis = self.coverage_analyzer.analyze_coverage_gaps()
        
        summary = {
            "executive_summary": {
                "current_coverage": current_metrics.overall_coverage,
                "target_coverage": self.business_targets['overall_coverage'],
                "progress_percentage": (current_metrics.overall_coverage / self.business_targets['overall_coverage']) * 100,
                "business_impact": self._assess_business_impact(current_metrics)
            },
            "module_breakdown": self._generate_module_breakdown(coverage_analysis),
            "gap_analysis": self._generate_gap_analysis(coverage_analysis),
            "test_enhancement_opportunities": self._generate_test_enhancement_opportunities(coverage_analysis)
        }
        
        recommendations = self._generate_detailed_recommendations(current_metrics, coverage_analysis)
        priority_actions = self._generate_priority_actions(current_metrics, coverage_analysis)
        
        return CoverageReport(
            report_type=ReportType.DETAILED,
            generated_at=timestamp,
            summary=summary,
            detailed_analysis=coverage_analysis,
            recommendations=recommendations,
            priority_actions=priority_actions
        )
    
    def _generate_trend_report(self, timestamp: str) -> CoverageReport:
        """Generate trend analysis report"""
        current_metrics = self.record_coverage_snapshot()
        trend_7_days = self.get_coverage_trend(7)
        trend_30_days = self.get_coverage_trend(30)
        
        summary = {
            "current_status": {
                "coverage": current_metrics.overall_coverage,
                "critical_coverage": current_metrics.critical_module_coverage,
                "business_gaps": current_metrics.business_critical_gaps
            },
            "7_day_trend": {
                "improvement_rate": trend_7_days.improvement_rate,
                "regression_count": trend_7_days.regression_count,
                "target_progress": trend_7_days.target_progress
            },
            "30_day_trend": {
                "improvement_rate": trend_30_days.improvement_rate,
                "regression_count": trend_30_days.regression_count,
                "target_progress": trend_30_days.target_progress
            },
            "velocity": self._calculate_velocity(trend_30_days),
            "eta_to_target": self._calculate_eta_to_target(trend_30_days, current_metrics),
            "trend_analysis": self._analyze_trends(trend_7_days, trend_30_days)
        }
        
        recommendations = self._generate_trend_recommendations(trend_7_days, trend_30_days)
        priority_actions = self._generate_trend_priority_actions(trend_7_days, trend_30_days)
        
        return CoverageReport(
            report_type=ReportType.TREND,
            generated_at=timestamp,
            summary=summary,
            trend_analysis=trend_30_days,
            recommendations=recommendations,
            priority_actions=priority_actions
        )
    
    def _generate_business_impact_report(self, timestamp: str) -> CoverageReport:
        """Generate business impact focused report"""
        current_metrics = self.record_coverage_snapshot()
        coverage_analysis = self.coverage_analyzer.analyze_coverage_gaps()
        
        # Calculate business impact
        business_impact = self._calculate_detailed_business_impact(current_metrics, coverage_analysis)
        
        summary = {
            "storm_logger_empire_status": {
                "foundation_health": business_impact['foundation_health'],
                "revenue_risk": business_impact['revenue_risk'],
                "market_readiness": business_impact['market_readiness']
            },
            "critical_business_modules": business_impact['critical_modules'],
            "enterprise_readiness": business_impact['enterprise_readiness'],
            "revenue_impact_analysis": business_impact['revenue_impact'],
            "competitive_advantage_status": business_impact['competitive_advantage'],
            "customer_impact": business_impact['customer_impact']
        }
        
        recommendations = self._generate_business_recommendations(business_impact)
        priority_actions = self._generate_business_priority_actions(business_impact)
        
        return CoverageReport(
            report_type=ReportType.BUSINESS_IMPACT,
            generated_at=timestamp,
            summary=summary,
            detailed_analysis=coverage_analysis,
            recommendations=recommendations,
            priority_actions=priority_actions
        )
    
    def _generate_prioritized_report(self, timestamp: str) -> CoverageReport:
        """Generate prioritized action report"""
        current_metrics = self.record_coverage_snapshot()
        coverage_analysis = self.coverage_analyzer.analyze_coverage_gaps()
        
        # Prioritize modules by business impact
        prioritized_modules = self._prioritize_modules_by_business_impact(coverage_analysis)
        
        summary = {
            "prioritized_modules": prioritized_modules,
            "quick_wins": self._identify_quick_wins(coverage_analysis),
            "high_impact_low_effort": self._identify_high_impact_low_effort(coverage_analysis),
            "critical_path": self._identify_critical_path(coverage_analysis),
            "resource_allocation": self._suggest_resource_allocation(coverage_analysis),
            "timeline_estimate": self._estimate_timeline(coverage_analysis)
        }
        
        recommendations = self._generate_prioritized_recommendations(prioritized_modules)
        priority_actions = self._generate_prioritized_actions(prioritized_modules)
        
        return CoverageReport(
            report_type=ReportType.PRIORITIZED,
            generated_at=timestamp,
            summary=summary,
            detailed_analysis=coverage_analysis,
            recommendations=recommendations,
            priority_actions=priority_actions
        )
    
    def _assess_business_impact(self, metrics: CoverageMetrics) -> str:
        """Assess business impact of current coverage"""
        if metrics.business_critical_gaps > 0:
            return "HIGH - Business-critical modules lack adequate coverage"
        elif metrics.overall_coverage < 75:
            return "MEDIUM - Overall coverage below enterprise standards"
        elif metrics.security_critical_gaps > 0:
            return "MEDIUM - Security modules need attention"
        else:
            return "LOW - Coverage meets basic requirements"
    
    def _calculate_detailed_business_impact(self, metrics: CoverageMetrics, analysis: CoverageAnalysisResult) -> Dict[str, Any]:
        """Calculate detailed business impact analysis"""
        # Foundation health (Storm Logger as foundation for $50M empire)
        foundation_health = "EXCELLENT" if metrics.overall_coverage >= 90 else "GOOD" if metrics.overall_coverage >= 80 else "NEEDS_ATTENTION"
        
        # Revenue risk based on coverage gaps
        revenue_risk = "LOW" if metrics.business_critical_gaps == 0 else "MEDIUM" if metrics.business_critical_gaps <= 2 else "HIGH"
        
        # Market readiness
        market_readiness = "READY" if metrics.overall_coverage >= 90 and metrics.business_critical_gaps == 0 else "NEEDS_IMPROVEMENT"
        
        return {
            "foundation_health": foundation_health,
            "revenue_risk": revenue_risk,
            "market_readiness": market_readiness,
            "critical_modules": self._analyze_critical_modules(analysis),
            "enterprise_readiness": self._assess_enterprise_readiness(metrics),
            "revenue_impact": self._calculate_revenue_impact(metrics),
            "competitive_advantage": self._assess_competitive_advantage(metrics),
            "customer_impact": self._assess_customer_impact(metrics)
        }
    
    def _generate_recommendations(self, metrics: CoverageMetrics, analysis: CoverageAnalysisResult) -> List[str]:
        """Generate coverage improvement recommendations"""
        recommendations = []
        
        if metrics.business_critical_gaps > 0:
            recommendations.append("URGENT: Address business-critical module coverage gaps immediately")
        
        if metrics.security_critical_gaps > 0:
            recommendations.append("HIGH: Improve security module coverage for compliance")
        
        if metrics.overall_coverage < 85:
            recommendations.append("Implement comprehensive test generation for low-coverage modules")
        
        if metrics.performance_critical_gaps > 0:
            recommendations.append("Add performance testing to ensure 6M logs/sec capability")
        
        recommendations.append("Use Storm Logger MCP tools for automated test generation")
        recommendations.append("Prioritize modules by business impact for maximum ROI")
        
        return recommendations
    
    def _generate_priority_actions(self, metrics: CoverageMetrics, analysis: CoverageAnalysisResult) -> List[str]:
        """Generate priority actions"""
        actions = []
        
        # Top priority modules
        low_coverage_modules = [m for m in analysis.modules if m.coverage_percentage < 50]
        if low_coverage_modules:
            actions.append(f"Create comprehensive tests for {len(low_coverage_modules)} low-coverage modules")
        
        # Business critical actions
        if metrics.business_critical_gaps > 0:
            actions.append("Focus on business_metrics.py and sanitizer.py coverage")
        
        # Quick wins
        medium_coverage_modules = [m for m in analysis.modules if 50 <= m.coverage_percentage < 90]
        if medium_coverage_modules:
            actions.append(f"Enhance {len(medium_coverage_modules)} medium-coverage modules to 90%+")
        
        return actions
    
    def _get_priority_modules(self, analysis: CoverageAnalysisResult) -> List[Dict[str, Any]]:
        """Get priority modules for improvement"""
        modules = []
        
        for module in analysis.modules:
            if module.coverage_percentage < 90:
                priority = "HIGH" if any(crit in module.file_path.lower() for crit in self.business_critical_modules) else "MEDIUM"
                modules.append({
                    "module": module.file_path,
                    "coverage": module.coverage_percentage,
                    "priority": priority,
                    "missing_lines": len(module.missing_lines),
                    "uncovered_functions": len(module.uncovered_functions)
                })
        
        # Sort by priority and coverage
        modules.sort(key=lambda x: (x['priority'] == 'HIGH', 100 - x['coverage']))
        
        return modules[:10]  # Top 10 priority modules
    
    def _calculate_velocity(self, trend: CoverageTrend) -> float:
        """Calculate coverage improvement velocity"""
        if len(trend.metrics) < 2:
            return 0.0
        
        # Calculate average daily improvement
        first_metric = trend.metrics[0]
        last_metric = trend.metrics[-1]
        
        days_diff = (datetime.datetime.fromisoformat(last_metric.timestamp) - 
                    datetime.datetime.fromisoformat(first_metric.timestamp)).days
        
        if days_diff == 0:
            return 0.0
        
        coverage_diff = last_metric.overall_coverage - first_metric.overall_coverage
        return coverage_diff / days_diff
    
    def _calculate_eta_to_target(self, trend: CoverageTrend, current_metrics: CoverageMetrics) -> str:
        """Calculate ETA to reach target coverage"""
        velocity = self._calculate_velocity(trend)
        
        if velocity <= 0:
            return "Unable to estimate (no positive trend)"
        
        coverage_gap = self.business_targets['overall_coverage'] - current_metrics.overall_coverage
        days_to_target = coverage_gap / velocity
        
        if days_to_target <= 7:
            return f"~{int(days_to_target)} days"
        elif days_to_target <= 30:
            return f"~{int(days_to_target/7)} weeks"
        else:
            return f"~{int(days_to_target/30)} months"
    
    def export_coverage_data(self, format: str = "json") -> str:
        """Export coverage data for external analysis"""
        current_metrics = self.record_coverage_snapshot()
        trend_data = self.get_coverage_trend(30)
        
        export_data = {
            "export_timestamp": datetime.datetime.now().isoformat(),
            "current_metrics": current_metrics.to_dict(),
            "trend_data": trend_data.to_dict(),
            "business_targets": self.business_targets,
            "business_critical_modules": self.business_critical_modules
        }
        
        if format.lower() == "json":
            return json.dumps(export_data, indent=2)
        else:
            return str(export_data)
    
    # Helper methods for detailed analysis
    def _generate_module_breakdown(self, analysis: CoverageAnalysisResult) -> Dict[str, Any]:
        """Generate detailed module breakdown"""
        breakdown = {
            "by_category": {},
            "by_coverage_level": {},
            "critical_modules": {},
            "improvement_opportunities": []
        }
        
        # Categorize modules
        for module in analysis.modules:
            category = "business_critical" if any(crit in module.file_path.lower() for crit in self.business_critical_modules) else "standard"
            
            if category not in breakdown["by_category"]:
                breakdown["by_category"][category] = []
            
            breakdown["by_category"][category].append({
                "module": module.file_path,
                "coverage": module.coverage_percentage,
                "missing_lines": len(module.missing_lines),
                "uncovered_functions": len(module.uncovered_functions)
            })
        
        return breakdown
    
    def _prioritize_modules_by_business_impact(self, analysis: CoverageAnalysisResult) -> List[Dict[str, Any]]:
        """Prioritize modules by business impact"""
        modules = []
        
        for module in analysis.modules:
            business_impact_score = 0
            
            # Business critical modules get highest priority
            if any(crit in module.file_path.lower() for crit in self.business_critical_modules):
                business_impact_score += 100
            
            # Performance critical modules
            if 'performance' in module.file_path.lower() or 'logger' in module.file_path.lower():
                business_impact_score += 75
            
            # Security critical modules
            if any(sec in module.file_path.lower() for sec in ['sanitizer', 'security', 'patterns']):
                business_impact_score += 90
            
            # Enterprise modules
            if any(ent in module.file_path.lower() for ent in ['django', 'professional', 'enterprise']):
                business_impact_score += 80
            
            # Coverage gap penalty
            coverage_gap = 100 - module.coverage_percentage
            business_impact_score += coverage_gap * 0.5
            
            modules.append({
                "module": module.file_path,
                "coverage": module.coverage_percentage,
                "business_impact_score": business_impact_score,
                "priority": "CRITICAL" if business_impact_score >= 150 else "HIGH" if business_impact_score >= 100 else "MEDIUM",
                "missing_lines": len(module.missing_lines),
                "uncovered_functions": len(module.uncovered_functions)
            })
        
        # Sort by business impact score
        modules.sort(key=lambda x: x['business_impact_score'], reverse=True)
        
        return modules[:15]  # Top 15 modules by business impact
    
    # Additional helper methods would continue here...
    def _analyze_critical_modules(self, analysis: CoverageAnalysisResult) -> Dict[str, Any]:
        """Analyze critical modules in detail"""
        critical_analysis = {"modules": [], "summary": {}}
        
        for module in analysis.modules:
            if any(crit in module.file_path.lower() for crit in self.business_critical_modules):
                critical_analysis["modules"].append({
                    "module": module.file_path,
                    "coverage": module.coverage_percentage,
                    "status": "GOOD" if module.coverage_percentage >= 90 else "NEEDS_ATTENTION",
                    "gap_to_target": max(0, 100 - module.coverage_percentage),
                    "missing_lines": len(module.missing_lines),
                    "uncovered_functions": len(module.uncovered_functions)
                })
        
        return critical_analysis
    
    def _assess_enterprise_readiness(self, metrics: CoverageMetrics) -> str:
        """Assess enterprise readiness based on coverage"""
        if metrics.overall_coverage >= 95 and metrics.business_critical_gaps == 0:
            return "ENTERPRISE_READY"
        elif metrics.overall_coverage >= 85 and metrics.business_critical_gaps <= 1:
            return "NEARLY_READY"
        else:
            return "NEEDS_IMPROVEMENT"
    
    def _calculate_revenue_impact(self, metrics: CoverageMetrics) -> Dict[str, Any]:
        """Calculate potential revenue impact"""
        # Based on Storm Logger's $50M empire strategy
        return {
            "risk_level": "HIGH" if metrics.business_critical_gaps > 2 else "MEDIUM" if metrics.business_critical_gaps > 0 else "LOW",
            "affected_products": self._identify_affected_products(metrics),
            "potential_revenue_at_risk": self._calculate_revenue_at_risk(metrics),
            "mitigation_priority": "IMMEDIATE" if metrics.business_critical_gaps > 0 else "STANDARD"
        }
    
    def _identify_affected_products(self, metrics: CoverageMetrics) -> List[str]:
        """Identify Storm products affected by coverage gaps"""
        affected = []
        
        if metrics.business_critical_gaps > 0:
            affected.extend(["Storm Test Framework", "Django-Spellbook Sites", "Dashboard Platform"])
        
        if metrics.performance_critical_gaps > 0:
            affected.extend(["High-Performance Logging", "6M logs/sec capability"])
        
        if metrics.security_critical_gaps > 0:
            affected.extend(["Enterprise Security", "Compliance Features"])
        
        return list(set(affected))
    
    def _calculate_revenue_at_risk(self, metrics: CoverageMetrics) -> str:
        """Calculate revenue at risk based on coverage gaps"""
        # Storm Logger empire revenue model
        risk_percentage = (metrics.business_critical_gaps * 10) + (metrics.security_critical_gaps * 15)
        risk_percentage = min(risk_percentage, 50)  # Cap at 50%
        
        if risk_percentage >= 30:
            return "HIGH ($5M+ at risk)"
        elif risk_percentage >= 15:
            return "MEDIUM ($1-5M at risk)"
        else:
            return "LOW (<$1M at risk)"


def generate_coverage_report(report_type: str = "summary") -> str:
    """
    MCP function to generate coverage report
    
    Args:
        report_type: Type of report (summary, detailed, trend, business_impact, prioritized)
        
    Returns:
        JSON string with coverage report
    """
    tracker = StormCoverageTracker()
    
    # Map string to enum
    report_type_enum = {
        "summary": ReportType.SUMMARY,
        "detailed": ReportType.DETAILED,
        "trend": ReportType.TREND,
        "business_impact": ReportType.BUSINESS_IMPACT,
        "prioritized": ReportType.PRIORITIZED
    }.get(report_type.lower(), ReportType.SUMMARY)
    
    report = tracker.generate_coverage_report(report_type_enum)
    
    return json.dumps(report.to_dict(), indent=2)


def record_coverage_snapshot() -> str:
    """
    MCP function to record current coverage snapshot
    
    Returns:
        JSON string with current coverage metrics
    """
    tracker = StormCoverageTracker()
    metrics = tracker.record_coverage_snapshot()
    
    return json.dumps(metrics.to_dict(), indent=2)


def get_coverage_trend(days: int = 30) -> str:
    """
    MCP function to get coverage trend analysis
    
    Args:
        days: Number of days to analyze
        
    Returns:
        JSON string with trend analysis
    """
    tracker = StormCoverageTracker()
    trend = tracker.get_coverage_trend(days)
    
    return json.dumps(trend.to_dict(), indent=2)


def export_coverage_data(format: str = "json") -> str:
    """
    MCP function to export coverage data
    
    Args:
        format: Export format (json, csv, etc.)
        
    Returns:
        Coverage data in requested format
    """
    tracker = StormCoverageTracker()
    return tracker.export_coverage_data(format)


def track_coverage_improvement(target_coverage: float = 90.0) -> str:
    """
    MCP function to track progress toward coverage target
    
    Args:
        target_coverage: Target coverage percentage
        
    Returns:
        JSON string with improvement tracking
    """
    tracker = StormCoverageTracker()
    current_metrics = tracker.record_coverage_snapshot()
    trend = tracker.get_coverage_trend(30)
    
    # Calculate progress
    progress = (current_metrics.overall_coverage / target_coverage) * 100
    
    improvement_tracking = {
        "target_coverage": target_coverage,
        "current_coverage": current_metrics.overall_coverage,
        "progress_percentage": progress,
        "gap_to_target": max(0, target_coverage - current_metrics.overall_coverage),
        "improvement_rate": trend.improvement_rate,
        "eta_to_target": tracker._calculate_eta_to_target(trend, current_metrics),
        "business_critical_gaps": current_metrics.business_critical_gaps,
        "recommendations": tracker._generate_recommendations(current_metrics, tracker.coverage_analyzer.analyze_coverage_gaps()),
        "priority_actions": tracker._generate_priority_actions(current_metrics, tracker.coverage_analyzer.analyze_coverage_gaps())
    }
    
    return json.dumps(improvement_tracking, indent=2)