"""
CHRONOS Quantum Readiness Score Calculator
==========================================

Comprehensive quantum security readiness assessment with:
- 5-factor scoring system (1000 total points)
- Industry benchmarking against NIST guidelines
- Historical progress tracking
- Gap analysis with recommendations
- PDF report generation
"""

from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import json
import csv

try:
    from reportlab.lib.pagesizes import letter
    from reportlab.lib.units import inch
    from reportlab.lib import colors
    from reportlab.platypus import (
        SimpleDocTemplate,
        Table,
        TableStyle,
        Paragraph,
        Spacer,
        Image,
        PageBreak,
    )
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
    REPORTLAB_AVAILABLE = True
except ImportError:
    REPORTLAB_AVAILABLE = False

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.patches import Rectangle
import numpy as np


class ReadinessBenchmark(Enum):
    """NIST quantum readiness benchmark levels."""
    DEVELOPING = ("Developing", 1, 250)           # 0-250 points
    PREPARED = ("Prepared", 2, 500)                # 251-500 points
    ADVANCED = ("Advanced", 3, 750)                # 501-750 points
    LEADING = ("Leading", 4, 1000)                 # 751-1000 points


class CryptoInventoryLevel(Enum):
    """Cryptography inventory maturity levels."""
    NONE = 0                  # No inventory
    PARTIAL = 100             # <50% documented
    DOCUMENTED = 200          # 50-75% documented
    COMPREHENSIVE = 300       # 75-90% documented
    COMPLETE = 400            # >90% documented


class MigrationPhase(Enum):
    """PQC migration progress phases."""
    NOT_STARTED = 0           # 0%
    PLANNING = 62             # 10%
    ASSESSMENT = 125          # 25%
    PILOT = 187               # 50%
    DEPLOYMENT = 250          # 100%


class DetectionCapability(Enum):
    """Quantum threat detection capability levels."""
    NONE = 0                  # No detection
    MANUAL = 50               # Manual review only
    SEMI_AUTOMATED = 100      # Semi-automated scanning
    AUTOMATED = 150           # Fully automated detection


class ComplianceLevel(Enum):
    """Regulatory compliance status."""
    NON_COMPLIANT = 0         # No compliance
    PARTIAL = 25              # Some compliance
    ALIGNED = 50              # 50% aligned
    COMPLIANT = 100           # Fully compliant


class TrainingLevel(Enum):
    """Security awareness training status."""
    NONE = 0                  # No training
    BASIC = 25                # Awareness training only
    INTERMEDIATE = 50         # Role-specific training
    COMPREHENSIVE = 100       # Comprehensive, ongoing training


@dataclass
class ReadinessAssessment:
    """Individual readiness factor assessment."""
    name: str
    score: float
    max_score: float
    percentage: float
    status: str  # developing, prepared, advanced, leading
    maturity_level: int  # 1-4 scale
    recommendations: List[str] = field(default_factory=list)
    evidence: Dict[str, any] = field(default_factory=dict)


@dataclass
class GapAnalysis:
    """Gap analysis with actionable recommendations."""
    factor: str
    current_score: float
    target_score: float
    gap_size: float
    gap_percentage: float
    priority: str  # critical, high, medium, low
    recommendations: List[str] = field(default_factory=list)
    estimated_effort_hours: float = 0.0
    estimated_completion_months: float = 0.0


@dataclass
class HistoricalSnapshot:
    """Historical readiness snapshot for tracking progress."""
    timestamp: datetime
    overall_score: float
    crypto_inventory: float
    migration: float
    detection: float
    compliance: float
    training: float
    benchmark_level: str


@dataclass
class ReadinessScoreResult:
    """Complete readiness scoring result."""
    assessment_date: datetime
    organization_name: str
    overall_score: float
    overall_percentage: float
    benchmark_level: str
    maturity_level: int
    
    # Factor scores
    crypto_inventory: ReadinessAssessment
    migration: ReadinessAssessment
    detection: ReadinessAssessment
    compliance: ReadinessAssessment
    training: ReadinessAssessment
    
    # Analysis
    gap_analysis: List[GapAnalysis]
    historical_data: List[HistoricalSnapshot] = field(default_factory=list)
    
    # Recommendations
    recommendations: List[str] = field(default_factory=list)
    action_plan: List[Tuple[str, int, str]] = field(default_factory=list)  # (action, months, priority)


class QuantumReadinessCalculator:
    """Calculate quantum security readiness score."""
    
    def __init__(self, verbose: bool = False):
        """Initialize readiness calculator."""
        self.verbose = verbose
        self.historical_snapshots: List[HistoricalSnapshot] = []
    
    def calculate_readiness_score(
        self,
        organization_name: str = "Organization",
        crypto_inventory_level: int = 0,
        migration_progress_percent: float = 0.0,
        detection_capability: int = 0,
        compliance_status: int = 0,
        training_level: int = 0,
        historical_snapshots: Optional[List[HistoricalSnapshot]] = None,
    ) -> ReadinessScoreResult:
        """
        Calculate comprehensive quantum readiness score.
        
        Args:
            organization_name: Organization name for reporting
            crypto_inventory_level: 0-400 points
            migration_progress_percent: 0-100% (scales to 0-250)
            detection_capability: 0-150 points
            compliance_status: 0-100 points
            training_level: 0-100 points
            historical_snapshots: Previous assessments for trend analysis
            
        Returns:
            ReadinessScoreResult with comprehensive assessment
        """
        
        # Validate and normalize inputs
        crypto_inventory = max(0, min(400, float(crypto_inventory_level)))
        migration = max(0, min(250, (migration_progress_percent / 100.0) * 250))
        detection = max(0, min(150, float(detection_capability)))
        compliance = max(0, min(100, float(compliance_status)))
        training = max(0, min(100, float(training_level)))
        
        # Calculate overall score
        overall_score = crypto_inventory + migration + detection + compliance + training
        overall_percentage = (overall_score / 1000.0) * 100.0
        
        # Determine benchmark level
        benchmark = self._get_benchmark_level(overall_score)
        
        # Create assessment objects for each factor
        crypto_assessment = self._assess_crypto_inventory(crypto_inventory)
        migration_assessment = self._assess_migration(migration)
        detection_assessment = self._assess_detection(detection)
        compliance_assessment = self._assess_compliance(compliance)
        training_assessment = self._assess_training(training)
        
        # Perform gap analysis
        gaps = self._perform_gap_analysis(
            crypto_assessment,
            migration_assessment,
            detection_assessment,
            compliance_assessment,
            training_assessment,
        )
        
        # Generate recommendations
        recommendations = self._generate_recommendations(gaps)
        action_plan = self._generate_action_plan(gaps)
        
        # Create result
        result = ReadinessScoreResult(
            assessment_date=datetime.now(),
            organization_name=organization_name,
            overall_score=overall_score,
            overall_percentage=overall_percentage,
            benchmark_level=benchmark,
            maturity_level=self._get_maturity_level(overall_score),
            crypto_inventory=crypto_assessment,
            migration=migration_assessment,
            detection=detection_assessment,
            compliance=compliance_assessment,
            training=training_assessment,
            gap_analysis=gaps,
            historical_data=historical_snapshots or [],
            recommendations=recommendations,
            action_plan=action_plan,
        )
        
        # Store historical snapshot
        snapshot = HistoricalSnapshot(
            timestamp=datetime.now(),
            overall_score=overall_score,
            crypto_inventory=crypto_inventory,
            migration=migration,
            detection=detection,
            compliance=compliance,
            training=training,
            benchmark_level=benchmark,
        )
        self.historical_snapshots.append(snapshot)
        
        if self.verbose:
            print(f"Readiness Assessment Complete: {overall_score:.1f}/1000 ({overall_percentage:.1f}%)")
        
        return result
    
    def _get_benchmark_level(self, score: float) -> str:
        """Get NIST benchmark level for score."""
        if score <= 250:
            return ReadinessBenchmark.DEVELOPING.value[0]
        elif score <= 500:
            return ReadinessBenchmark.PREPARED.value[0]
        elif score <= 750:
            return ReadinessBenchmark.ADVANCED.value[0]
        else:
            return ReadinessBenchmark.LEADING.value[0]
    
    def _get_maturity_level(self, score: float) -> int:
        """Get maturity level (1-4 scale)."""
        if score <= 250:
            return 1
        elif score <= 500:
            return 2
        elif score <= 750:
            return 3
        else:
            return 4
    
    def _assess_crypto_inventory(self, score: float) -> ReadinessAssessment:
        """Assess cryptography inventory factor."""
        percentage = (score / 400.0) * 100.0
        
        if score < 100:
            status = "Developing"
            level = 1
            recommendations = [
                "Initiate cryptography inventory project",
                "Document all cryptographic systems",
                "Identify key management systems",
                "Create asset tracking database",
            ]
        elif score < 200:
            status = "Prepared"
            level = 2
            recommendations = [
                "Complete partial inventory documentation",
                "Identify missing systems (>50% documented)",
                "Begin algorithm classification",
                "Document key sizes and expiration dates",
            ]
        elif score < 300:
            status = "Advanced"
            level = 3
            recommendations = [
                "Achieve >75% inventory completion",
                "Validate all documented assets",
                "Create remediation priority list",
                "Establish inventory governance process",
            ]
        else:
            status = "Leading"
            level = 4
            recommendations = [
                "Maintain >90% inventory accuracy",
                "Implement continuous discovery",
                "Establish quarterly audit process",
                "Integrate with vulnerability scanning",
            ]
        
        return ReadinessAssessment(
            name="Cryptography Inventory",
            score=score,
            max_score=400,
            percentage=percentage,
            status=status,
            maturity_level=level,
            recommendations=recommendations,
            evidence={"coverage_percent": percentage},
        )
    
    def _assess_migration(self, score: float) -> ReadinessAssessment:
        """Assess PQC migration progress factor."""
        percentage = (score / 250.0) * 100.0
        progress_percent = percentage
        
        if score < 62:
            status = "Developing"
            level = 1
            recommendations = [
                "Initiate PQC migration planning",
                "Form migration steering committee",
                "Develop migration roadmap (5-year plan)",
                "Identify key stakeholders",
            ]
        elif score < 125:
            status = "Preparing"
            level = 2
            recommendations = [
                "Complete migration assessment",
                "Evaluate NIST PQC standards (FIPS 203-205)",
                "Select target PQC algorithms",
                "Develop implementation timeline",
            ]
        elif score < 187:
            status = "Piloting"
            level = 3
            recommendations = [
                "Deploy PQC pilots (non-critical systems)",
                "Test ML-KEM and ML-DSA integration",
                "Validate interoperability",
                "Plan production rollout",
            ]
        else:
            status = "Deploying"
            level = 4
            recommendations = [
                "Deploy to production systems",
                "Migrate high-value assets first",
                "Establish post-migration validation",
                "Plan full operational deployment",
            ]
        
        return ReadinessAssessment(
            name="PQC Migration",
            score=score,
            max_score=250,
            percentage=percentage,
            status=status,
            maturity_level=level,
            recommendations=recommendations,
            evidence={"progress_percent": progress_percent},
        )
    
    def _assess_detection(self, score: float) -> ReadinessAssessment:
        """Assess threat detection capability factor."""
        percentage = (score / 150.0) * 100.0
        
        if score < 50:
            status = "Developing"
            level = 1
            recommendations = [
                "Deploy threat detection tools",
                "Implement manual scanning process",
                "Create detection playbooks",
                "Establish baseline metrics",
            ]
        elif score < 100:
            status = "Semi-Automated"
            level = 2
            recommendations = [
                "Automate detection workflows",
                "Integrate with SIEM system",
                "Create automated response triggers",
                "Establish detection SLAs",
            ]
        elif score < 125:
            status = "Automated"
            level = 3
            recommendations = [
                "Deploy full automation",
                "Implement ML-based detection",
                "Create real-time alerts",
                "Establish continuous monitoring",
            ]
        else:
            status = "Advanced"
            level = 4
            recommendations = [
                "Enhance detection accuracy",
                "Implement predictive detection",
                "Establish threat hunting program",
                "Perform annual detection validation",
            ]
        
        return ReadinessAssessment(
            name="Threat Detection",
            score=score,
            max_score=150,
            percentage=percentage,
            status=status,
            maturity_level=level,
            recommendations=recommendations,
            evidence={"automation_percent": percentage},
        )
    
    def _assess_compliance(self, score: float) -> ReadinessAssessment:
        """Assess regulatory compliance factor."""
        percentage = (score / 100.0) * 100.0
        
        if score < 25:
            status = "Non-Compliant"
            level = 1
            recommendations = [
                "Assess compliance requirements (NIST, HIPAA, PCI DSS)",
                "Document compliance gaps",
                "Develop compliance roadmap",
                "Allocate compliance resources",
            ]
        elif score < 50:
            status = "Partial"
            level = 2
            recommendations = [
                "Achieve 50% compliance alignment",
                "Close critical gaps",
                "Implement compliance controls",
                "Establish audit schedule",
            ]
        elif score < 75:
            status = "Aligned"
            level = 3
            recommendations = [
                "Achieve >75% compliance",
                "Address remaining gaps",
                "Implement monitoring controls",
                "Schedule compliance audit",
            ]
        else:
            status = "Compliant"
            level = 4
            recommendations = [
                "Maintain full compliance",
                "Perform quarterly assessments",
                "Update compliance policies",
                "Conduct annual audits",
            ]
        
        return ReadinessAssessment(
            name="Regulatory Compliance",
            score=score,
            max_score=100,
            percentage=percentage,
            status=status,
            maturity_level=level,
            recommendations=recommendations,
            evidence={"compliance_percent": percentage},
        )
    
    def _assess_training(self, score: float) -> ReadinessAssessment:
        """Assess security training and awareness factor."""
        percentage = (score / 100.0) * 100.0
        
        if score < 25:
            status = "None"
            level = 1
            recommendations = [
                "Develop training program",
                "Create awareness curriculum",
                "Train leadership first",
                "Establish training metrics",
            ]
        elif score < 50:
            status = "Basic"
            level = 2
            recommendations = [
                "Expand training to all staff",
                "Add role-specific training",
                "Create certification program",
                "Establish competency requirements",
            ]
        elif score < 75:
            status = "Intermediate"
            level = 3
            recommendations = [
                "Implement intermediate-level training",
                "Create ongoing training program",
                "Establish quarterly updates",
                "Measure training effectiveness",
            ]
        else:
            status = "Comprehensive"
            level = 4
            recommendations = [
                "Maintain comprehensive training",
                "Update curriculum annually",
                "Conduct advanced certifications",
                "Establish thought leadership",
            ]
        
        return ReadinessAssessment(
            name="Training & Awareness",
            score=score,
            max_score=100,
            percentage=percentage,
            status=status,
            maturity_level=level,
            recommendations=recommendations,
            evidence={"trained_percent": percentage},
        )
    
    def _perform_gap_analysis(
        self,
        crypto: ReadinessAssessment,
        migration: ReadinessAssessment,
        detection: ReadinessAssessment,
        compliance: ReadinessAssessment,
        training: ReadinessAssessment,
    ) -> List[GapAnalysis]:
        """Perform gap analysis for each factor."""
        gaps = []
        
        factors = [
            (crypto, 400, "Cryptography Inventory"),
            (migration, 250, "PQC Migration"),
            (detection, 150, "Threat Detection"),
            (compliance, 100, "Regulatory Compliance"),
            (training, 100, "Training & Awareness"),
        ]
        
        for assessment, max_score, name in factors:
            current = assessment.score
            target = max_score
            gap = target - current
            gap_pct = (gap / target) * 100 if target > 0 else 0
            
            # Determine priority based on gap size
            if gap_pct == 0:
                priority = "complete"
            elif gap_pct < 10:
                priority = "low"
            elif gap_pct < 25:
                priority = "medium"
            else:
                priority = "high"
            
            # Estimate effort (hours and months)
            effort_hours = gap_pct * 10  # Rough estimate
            effort_months = max(0.5, effort_hours / 160)  # Assuming 160 hours/month
            
            gap_analysis = GapAnalysis(
                factor=name,
                current_score=current,
                target_score=target,
                gap_size=gap,
                gap_percentage=gap_pct,
                priority=priority,
                recommendations=assessment.recommendations,
                estimated_effort_hours=effort_hours,
                estimated_completion_months=effort_months,
            )
            gaps.append(gap_analysis)
        
        # Sort by priority and gap size
        priority_order = {"critical": 0, "high": 1, "medium": 2, "low": 3, "complete": 4}
        gaps.sort(key=lambda x: (priority_order.get(x.priority, 5), -x.gap_size))
        
        return gaps
    
    def _generate_recommendations(self, gaps: List[GapAnalysis]) -> List[str]:
        """Generate high-level recommendations from gaps."""
        recommendations = []
        
        # Critical gaps
        critical_gaps = [g for g in gaps if g.gap_percentage > 50]
        if critical_gaps:
            recommendations.append(
                f"CRITICAL: {len(critical_gaps)} major gaps identified. "
                f"Estimated {sum(g.estimated_effort_hours for g in critical_gaps):.0f} hours to address."
            )
        
        # Top priority
        if gaps and gaps[0].gap_percentage > 0:
            recommendations.append(
                f"Priority 1: {gaps[0].factor} - "
                f"Close {gaps[0].gap_size:.0f}-point gap (~{gaps[0].estimated_completion_months:.1f} months)"
            )
        
        # Compliance focus
        compliance_gap = next((g for g in gaps if "Compliance" in g.factor), None)
        if compliance_gap and compliance_gap.gap_percentage > 25:
            recommendations.append(
                "URGENT: Address regulatory compliance gaps to avoid audit findings"
            )
        
        # Migration timeline
        migration_gap = next((g for g in gaps if "Migration" in g.factor), None)
        if migration_gap and migration_gap.gap_percentage > 50:
            recommendations.append(
                f"Accelerate PQC migration planning - currently at {100-migration_gap.gap_percentage:.0f}% progress"
            )
        
        # Training priority
        training_gap = next((g for g in gaps if "Training" in g.factor), None)
        if training_gap and training_gap.gap_percentage > 50:
            recommendations.append(
                "Initiate security awareness training immediately - "
                "critical for successful migration"
            )
        
        return recommendations
    
    def _generate_action_plan(self, gaps: List[GapAnalysis]) -> List[Tuple[str, int, str]]:
        """Generate action plan with timeline and priority."""
        actions = []
        
        # Map gaps to actions
        for gap in gaps:
            if gap.gap_percentage == 0:
                continue
            
            action = f"Close {gap.factor} gap ({gap.gap_size:.0f} points)"
            months = int(gap.estimated_completion_months)
            priority = gap.priority
            actions.append((action, months, priority))
        
        return actions
    
    def plot_readiness_overview(self, result: ReadinessScoreResult, save_path: Optional[str] = None):
        """Generate readiness overview visualization."""
        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(14, 10))
        fig.suptitle(f"Quantum Readiness Assessment - {result.organization_name}", fontsize=16, fontweight='bold')
        
        # 1. Overall Score Gauge (top-left)
        ax1.set_xlim(0, 10)
        ax1.set_ylim(0, 10)
        ax1.axis('off')
        
        # Benchmark colors
        colors_map = {
            "Developing": '#d62728',
            "Prepared": '#ff7f0e',
            "Advanced": '#2ca02c',
            "Leading": '#1f77b4',
        }
        
        color = colors_map.get(result.benchmark_level, '#808080')
        
        # Draw gauge
        circle = plt.Circle((5, 3), 2.5, color=color, alpha=0.3)
        ax1.add_patch(circle)
        ax1.text(5, 3, f"{result.overall_score:.0f}", ha='center', va='center', 
                fontsize=40, fontweight='bold')
        ax1.text(5, 1, f"{result.overall_percentage:.1f}%\n{result.benchmark_level}", 
                ha='center', va='center', fontsize=12, fontweight='bold')
        
        # 2. Factor Scores (top-right)
        factors = ['Inventory', 'Migration', 'Detection', 'Compliance', 'Training']
        scores = [
            result.crypto_inventory.score,
            result.migration.score,
            result.detection.score,
            result.compliance.score,
            result.training.score,
        ]
        max_scores = [400, 250, 150, 100, 100]
        percentages = [s/m*100 for s, m in zip(scores, max_scores)]
        
        bars = ax2.barh(factors, percentages, color=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd'])
        ax2.set_xlabel('Percentage (%)')
        ax2.set_title('Factor Scores')
        ax2.set_xlim(0, 100)
        
        # Add value labels
        for i, (bar, pct) in enumerate(zip(bars, percentages)):
            ax2.text(pct + 2, i, f'{pct:.0f}%', va='center', fontweight='bold')
        
        # 3. Gap Analysis (bottom-left)
        gap_factors = [g.factor.split()[0] for g in result.gap_analysis]
        gap_sizes = [g.gap_percentage for g in result.gap_analysis]
        gap_colors = ['#d62728' if g > 50 else '#ff7f0e' if g > 25 else '#2ca02c' for g in gap_sizes]
        
        ax3.barh(gap_factors, gap_sizes, color=gap_colors)
        ax3.set_xlabel('Gap (%)')
        ax3.set_title('Gap Analysis')
        ax3.set_xlim(0, 100)
        
        for i, (gap, pct) in enumerate(zip(gap_factors, gap_sizes)):
            if pct > 0:
                ax3.text(pct + 2, i, f'{pct:.0f}%', va='center')
        
        # 4. Maturity Level (bottom-right)
        levels = ['Developing', 'Prepared', 'Advanced', 'Leading']
        current_level = result.maturity_level
        
        for i, level in enumerate(levels):
            color = '#2ca02c' if i < current_level else '#cccccc'
            rect = Rectangle((i*2, 0), 1.8, 3, linewidth=2, edgecolor='black', facecolor=color)
            ax4.add_patch(rect)
            ax4.text(i*2+0.9, 1.5, str(i+1), ha='center', va='center', fontsize=20, fontweight='bold')
            ax4.text(i*2+0.9, 0.5, level, ha='center', va='bottom', fontsize=9)
        
        ax4.set_xlim(-0.5, 8.5)
        ax4.set_ylim(0, 3.5)
        ax4.axis('off')
        ax4.set_title('Maturity Level')
        
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')
            if self.verbose:
                print(f"✓ Saved readiness overview to {save_path}")
        
        return fig
    
    def plot_gap_analysis(self, result: ReadinessScoreResult, save_path: Optional[str] = None):
        """Generate detailed gap analysis visualization."""
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
        fig.suptitle(f"Gap Analysis & Action Plan - {result.organization_name}", fontsize=14, fontweight='bold')
        
        # Gap details
        gaps_data = result.gap_analysis
        factors = [g.factor for g in gaps_data]
        current = [g.current_score for g in gaps_data]
        gaps = [g.gap_size for g in gaps_data]
        
        x = np.arange(len(factors))
        width = 0.35
        
        bars1 = ax1.bar(x - width/2, current, width, label='Current', color='#2ca02c')
        bars2 = ax1.bar(x + width/2, gaps, width, label='Gap', color='#d62728')
        
        ax1.set_ylabel('Points')
        ax1.set_title('Current State vs. Gaps')
        ax1.set_xticks(x)
        ax1.set_xticklabels([f.split()[0] for f in factors], rotation=45)
        ax1.legend()
        ax1.grid(axis='y', alpha=0.3)
        
        # Add value labels
        for bars in [bars1, bars2]:
            for bar in bars:
                height = bar.get_height()
                if height > 0:
                    ax1.text(bar.get_x() + bar.get_width()/2., height,
                            f'{height:.0f}', ha='center', va='bottom', fontsize=8)
        
        # Effort estimation (hours and months)
        efforts_hours = [g.estimated_effort_hours for g in gaps_data]
        efforts_months = [g.estimated_completion_months for g in gaps_data]
        
        colors_effort = ['#d62728' if e > 100 else '#ff7f0e' if e > 50 else '#2ca02c' 
                        for e in efforts_hours]
        
        bars = ax2.barh(factors, efforts_months, color=colors_effort)
        ax2.set_xlabel('Estimated Months')
        ax2.set_title('Effort Estimation')
        
        for i, (bar, hours, months) in enumerate(zip(bars, efforts_hours, efforts_months)):
            ax2.text(months + 0.1, i, f'{months:.1f}m ({hours:.0f}h)', va='center', fontsize=9)
        
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')
            if self.verbose:
                print(f"✓ Saved gap analysis to {save_path}")
        
        return fig
    
    def plot_progress_trend(self, save_path: Optional[str] = None):
        """Generate progress trend visualization."""
        if len(self.historical_snapshots) < 2:
            if self.verbose:
                print("⚠ Insufficient historical data for trend analysis (need ≥2 snapshots)")
            return None
        
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
        fig.suptitle("Quantum Readiness Progress Over Time", fontsize=14, fontweight='bold')
        
        snapshots = self.historical_snapshots
        dates = [s.timestamp.strftime('%Y-%m-%d') for s in snapshots]
        overall = [s.overall_score for s in snapshots]
        
        # Overall score trend
        ax1.plot(dates, overall, marker='o', linewidth=2, markersize=8, color='#1f77b4')
        ax1.fill_between(range(len(dates)), overall, alpha=0.3, color='#1f77b4')
        ax1.set_ylabel('Overall Score (0-1000)')
        ax1.set_title('Overall Readiness Score Trend')
        ax1.grid(True, alpha=0.3)
        ax1.set_ylim(0, 1000)
        
        # Add value labels
        for x, y in enumerate(overall):
            ax1.text(x, y + 20, f'{y:.0f}', ha='center', fontweight='bold')
        
        # Factor comparison
        factors_data = {
            'Inventory': [s.crypto_inventory for s in snapshots],
            'Migration': [s.migration for s in snapshots],
            'Detection': [s.detection for s in snapshots],
            'Compliance': [s.compliance for s in snapshots],
            'Training': [s.training for s in snapshots],
        }
        
        colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
        
        for (factor, values), color in zip(factors_data.items(), colors):
            ax2.plot(dates, values, marker='o', label=factor, color=color, linewidth=2)
        
        ax2.set_ylabel('Points')
        ax2.set_title('Factor Scores Over Time')
        ax2.legend(loc='best')
        ax2.grid(True, alpha=0.3)
        
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')
            if self.verbose:
                print(f"✓ Saved progress trend to {save_path}")
        
        return fig
    
    def export_readiness_json(self, result: ReadinessScoreResult, filepath: str):
        """Export readiness assessment to JSON."""
        data = {
            "timestamp": result.assessment_date.isoformat(),
            "organization": result.organization_name,
            "summary": {
                "overall_score": result.overall_score,
                "overall_percentage": result.overall_percentage,
                "benchmark_level": result.benchmark_level,
                "maturity_level": result.maturity_level,
            },
            "factor_scores": {
                "crypto_inventory": {
                    "score": result.crypto_inventory.score,
                    "max_score": result.crypto_inventory.max_score,
                    "percentage": result.crypto_inventory.percentage,
                    "status": result.crypto_inventory.status,
                },
                "migration": {
                    "score": result.migration.score,
                    "max_score": result.migration.max_score,
                    "percentage": result.migration.percentage,
                    "status": result.migration.status,
                },
                "detection": {
                    "score": result.detection.score,
                    "max_score": result.detection.max_score,
                    "percentage": result.detection.percentage,
                    "status": result.detection.status,
                },
                "compliance": {
                    "score": result.compliance.score,
                    "max_score": result.compliance.max_score,
                    "percentage": result.compliance.percentage,
                    "status": result.compliance.status,
                },
                "training": {
                    "score": result.training.score,
                    "max_score": result.training.max_score,
                    "percentage": result.training.percentage,
                    "status": result.training.status,
                },
            },
            "gaps": [
                {
                    "factor": g.factor,
                    "current_score": g.current_score,
                    "target_score": g.target_score,
                    "gap_size": g.gap_size,
                    "gap_percentage": g.gap_percentage,
                    "priority": g.priority,
                    "estimated_effort_hours": g.estimated_effort_hours,
                    "estimated_completion_months": g.estimated_completion_months,
                }
                for g in result.gap_analysis
            ],
            "recommendations": result.recommendations,
            "action_plan": [
                {"action": a[0], "months": a[1], "priority": a[2]}
                for a in result.action_plan
            ],
        }
        
        with open(filepath, 'w') as f:
            json.dump(data, f, indent=2)
        
        if self.verbose:
            print(f"✓ Exported readiness assessment to {filepath}")
    
    def export_readiness_csv(self, result: ReadinessScoreResult, filepath: str):
        """Export readiness assessment to CSV."""
        with open(filepath, 'w', newline='') as f:
            writer = csv.writer(f)
            
            # Header
            writer.writerow(['Quantum Readiness Assessment', result.organization_name])
            writer.writerow(['Assessment Date', result.assessment_date.strftime('%Y-%m-%d %H:%M:%S')])
            writer.writerow([])
            
            # Summary
            writer.writerow(['Overall Score', f"{result.overall_score:.0f}/1000"])
            writer.writerow(['Percentage', f"{result.overall_percentage:.1f}%"])
            writer.writerow(['Benchmark Level', result.benchmark_level])
            writer.writerow(['Maturity Level', f"{result.maturity_level}/4"])
            writer.writerow([])
            
            # Factor scores
            writer.writerow(['Factor', 'Current', 'Max', 'Percentage', 'Status'])
            writer.writerow([
                'Cryptography Inventory',
                f"{result.crypto_inventory.score:.0f}",
                f"{result.crypto_inventory.max_score:.0f}",
                f"{result.crypto_inventory.percentage:.1f}%",
                result.crypto_inventory.status,
            ])
            writer.writerow([
                'PQC Migration',
                f"{result.migration.score:.0f}",
                f"{result.migration.max_score:.0f}",
                f"{result.migration.percentage:.1f}%",
                result.migration.status,
            ])
            writer.writerow([
                'Threat Detection',
                f"{result.detection.score:.0f}",
                f"{result.detection.max_score:.0f}",
                f"{result.detection.percentage:.1f}%",
                result.detection.status,
            ])
            writer.writerow([
                'Regulatory Compliance',
                f"{result.compliance.score:.0f}",
                f"{result.compliance.max_score:.0f}",
                f"{result.compliance.percentage:.1f}%",
                result.compliance.status,
            ])
            writer.writerow([
                'Training & Awareness',
                f"{result.training.score:.0f}",
                f"{result.training.max_score:.0f}",
                f"{result.training.percentage:.1f}%",
                result.training.status,
            ])
            writer.writerow([])
            
            # Gaps
            writer.writerow(['Factor', 'Gap Size', 'Gap %', 'Priority', 'Effort (Hours)', 'Timeline (Months)'])
            for gap in result.gap_analysis:
                writer.writerow([
                    gap.factor,
                    f"{gap.gap_size:.0f}",
                    f"{gap.gap_percentage:.1f}%",
                    gap.priority,
                    f"{gap.estimated_effort_hours:.0f}",
                    f"{gap.estimated_completion_months:.1f}",
                ])
            writer.writerow([])
            
            # Recommendations
            writer.writerow(['Recommendations'])
            for i, rec in enumerate(result.recommendations, 1):
                writer.writerow([f"{i}. {rec}"])
        
        if self.verbose:
            print(f"✓ Exported readiness assessment to {filepath}")
    
    def generate_pdf_report(
        self,
        result: ReadinessScoreResult,
        filepath: str,
        include_visualizations: bool = True,
    ):
        """Generate comprehensive PDF report using reportlab."""
        if not REPORTLAB_AVAILABLE:
            raise ImportError("reportlab required for PDF generation. Install with: pip install reportlab")
        
        doc = SimpleDocTemplate(filepath, pagesize=letter)
        story = []
        styles = getSampleStyleSheet()
        
        # Custom styles
        title_style = ParagraphStyle(
            'CustomTitle',
            parent=styles['Heading1'],
            fontSize=24,
            textColor=colors.HexColor('#1f77b4'),
            spaceAfter=30,
            alignment=TA_CENTER,
            fontName='Helvetica-Bold',
        )
        
        heading_style = ParagraphStyle(
            'CustomHeading',
            parent=styles['Heading2'],
            fontSize=14,
            textColor=colors.HexColor('#1f77b4'),
            spaceAfter=12,
            spaceBefore=12,
            fontName='Helvetica-Bold',
        )
        
        # Title
        story.append(Paragraph(
            f"Quantum Readiness Assessment Report",
            title_style,
        ))
        story.append(Paragraph(
            f"{result.organization_name}",
            styles['Heading2'],
        ))
        story.append(Spacer(1, 0.2*inch))
        
        # Assessment metadata
        metadata = [
            ['Assessment Date:', result.assessment_date.strftime('%B %d, %Y')],
            ['Organization:', result.organization_name],
            ['Overall Score:', f"{result.overall_score:.0f}/1000"],
            ['Percentage:', f"{result.overall_percentage:.1f}%"],
            ['Benchmark Level:', result.benchmark_level],
            ['Maturity Level:', f"{result.maturity_level}/4"],
        ]
        
        table = Table(metadata, colWidths=[2*inch, 4*inch])
        table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (0, -1), colors.HexColor('#f0f0f0')),
            ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, -1), 10),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 12),
            ('GRID', (0, 0), (-1, -1), 1, colors.grey),
        ]))
        story.append(table)
        story.append(Spacer(1, 0.3*inch))
        
        # Factor scores section
        story.append(Paragraph("Factor Scores", heading_style))
        
        factor_data = [
            ['Factor', 'Current', 'Max', 'Percentage', 'Status'],
            ['Cryptography Inventory', 
             f"{result.crypto_inventory.score:.0f}",
             f"{result.crypto_inventory.max_score:.0f}",
             f"{result.crypto_inventory.percentage:.1f}%",
             result.crypto_inventory.status],
            ['PQC Migration',
             f"{result.migration.score:.0f}",
             f"{result.migration.max_score:.0f}",
             f"{result.migration.percentage:.1f}%",
             result.migration.status],
            ['Threat Detection',
             f"{result.detection.score:.0f}",
             f"{result.detection.max_score:.0f}",
             f"{result.detection.percentage:.1f}%",
             result.detection.status],
            ['Regulatory Compliance',
             f"{result.compliance.score:.0f}",
             f"{result.compliance.max_score:.0f}",
             f"{result.compliance.percentage:.1f}%",
             result.compliance.status],
            ['Training & Awareness',
             f"{result.training.score:.0f}",
             f"{result.training.max_score:.0f}",
             f"{result.training.percentage:.1f}%",
             result.training.status],
        ]
        
        table = Table(factor_data, colWidths=[2*inch, 0.9*inch, 0.9*inch, 1.2*inch, 1*inch])
        table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#1f77b4')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
            ('GRID', (0, 0), (-1, -1), 1, colors.grey),
            ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f5f5f5')]),
        ]))
        story.append(table)
        story.append(Spacer(1, 0.3*inch))
        
        # Gap analysis section
        story.append(Paragraph("Gap Analysis & Action Items", heading_style))
        
        gap_data = [
            ['Factor', 'Gap', 'Priority', 'Effort (Hours)', 'Timeline (Months)'],
        ]
        
        for gap in result.gap_analysis:
            gap_data.append([
                gap.factor,
                f"{gap.gap_percentage:.1f}%",
                gap.priority.upper(),
                f"{gap.estimated_effort_hours:.0f}",
                f"{gap.estimated_completion_months:.1f}",
            ])
        
        table = Table(gap_data, colWidths=[2*inch, 1*inch, 1.2*inch, 1.2*inch, 1.6*inch])
        table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#d62728')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
            ('GRID', (0, 0), (-1, -1), 1, colors.grey),
            ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f5f5f5')]),
        ]))
        story.append(table)
        story.append(Spacer(1, 0.3*inch))
        
        # Recommendations
        story.append(Paragraph("Key Recommendations", heading_style))
        
        rec_text = "<br/>".join([f"• {rec}" for rec in result.recommendations])
        story.append(Paragraph(rec_text, styles['Normal']))
        
        # Build PDF
        doc.build(story)
        
        if self.verbose:
            print(f"✓ Generated PDF report at {filepath}")
