"""
CHRONOS Readiness Score CLI Commands
====================================

Commands for quantum readiness assessment with scoring, benchmarking, and reporting.
"""

from typing import Optional
from pathlib import Path
from datetime import datetime

import typer
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress

from chronos.core.analyze.readiness_score import (
    QuantumReadinessCalculator,
    HistoricalSnapshot,
)

app = typer.Typer(help="Quantum readiness assessment tools")
console = Console()


def _add_sample_assessments() -> tuple:
    """Generate sample organizational readiness data."""
    assessments = {
        "Large Enterprise": {
            "crypto_inventory_level": 350,
            "migration_progress_percent": 45,
            "detection_capability": 110,
            "compliance_status": 80,
            "training_level": 70,
        },
        "Mid-Market": {
            "crypto_inventory_level": 250,
            "migration_progress_percent": 25,
            "detection_capability": 75,
            "compliance_status": 60,
            "training_level": 50,
        },
        "Small Organization": {
            "crypto_inventory_level": 150,
            "migration_progress_percent": 10,
            "detection_capability": 40,
            "compliance_status": 30,
            "training_level": 25,
        },
        "Financial Services": {
            "crypto_inventory_level": 380,
            "migration_progress_percent": 60,
            "detection_capability": 135,
            "compliance_status": 95,
            "training_level": 85,
        },
        "Healthcare": {
            "crypto_inventory_level": 320,
            "migration_progress_percent": 40,
            "detection_capability": 95,
            "compliance_status": 90,
            "training_level": 80,
        },
        "Government": {
            "crypto_inventory_level": 380,
            "migration_progress_percent": 55,
            "detection_capability": 130,
            "compliance_status": 100,
            "training_level": 95,
        },
    }
    return assessments


def _display_readiness_summary(result):
    """Display readiness assessment summary."""
    console.print()
    
    # Overall score
    overall_section = Panel(
        f"[bold cyan]{result.overall_score:.0f}/1000[/bold cyan]\n"
        f"({result.overall_percentage:.1f}%)\n"
        f"[bold green]{result.benchmark_level.upper()}[/bold green]\n"
        f"Maturity Level: {result.maturity_level}/4",
        title="Overall Readiness Score",
        border_style="cyan",
    )
    console.print(overall_section)
    
    # Factor scores table
    console.print("\n[bold cyan]Factor Scores:[/bold cyan]")
    table = Table(show_header=True, header_style="bold magenta")
    table.add_column("Factor", style="cyan")
    table.add_column("Score", justify="right", style="green")
    table.add_column("Max", justify="right")
    table.add_column("Percentage", justify="right")
    table.add_column("Status", style="yellow")
    
    factors = [
        (result.crypto_inventory, "Cryptography Inventory"),
        (result.migration, "PQC Migration"),
        (result.detection, "Threat Detection"),
        (result.compliance, "Regulatory Compliance"),
        (result.training, "Training & Awareness"),
    ]
    
    for assessment, name in factors:
        status_color = "green" if assessment.percentage >= 75 else "yellow" if assessment.percentage >= 50 else "red"
        table.add_row(
            name,
            f"{assessment.score:.0f}",
            f"{assessment.max_score:.0f}",
            f"{assessment.percentage:.1f}%",
            f"[{status_color}]{assessment.status}[/{status_color}]",
        )
    
    console.print(table)
    
    # Gap analysis
    console.print("\n[bold cyan]Gap Analysis:[/bold cyan]")
    gap_table = Table(show_header=True, header_style="bold magenta")
    gap_table.add_column("Factor", style="cyan")
    gap_table.add_column("Gap %", justify="right")
    gap_table.add_column("Priority", style="yellow")
    gap_table.add_column("Effort (Hours)", justify="right")
    gap_table.add_column("Timeline (Months)", justify="right")
    
    for gap in result.gap_analysis:
        priority_color = "red" if gap.priority == "high" else "yellow" if gap.priority == "medium" else "green"
        gap_table.add_row(
            gap.factor,
            f"{gap.gap_percentage:.1f}%",
            f"[{priority_color}]{gap.priority.upper()}[/{priority_color}]",
            f"{gap.estimated_effort_hours:.0f}",
            f"{gap.estimated_completion_months:.1f}",
        )
    
    console.print(gap_table)


@app.command()
def assess(
    organization: str = typer.Option(
        None,
        "--organization",
        help="Organization name for assessment"
    ),
    sample: bool = typer.Option(
        False,
        "--sample",
        help="Use sample organization data"
    ),
    crypto: int = typer.Option(
        None,
        "--crypto",
        help="Cryptography inventory score (0-400)"
    ),
    migration: float = typer.Option(
        None,
        "--migration",
        help="PQC migration progress percent (0-100)"
    ),
    detection: int = typer.Option(
        None,
        "--detection",
        help="Threat detection capability (0-150)"
    ),
    compliance: int = typer.Option(
        None,
        "--compliance",
        help="Regulatory compliance status (0-100)"
    ),
    training: int = typer.Option(
        None,
        "--training",
        help="Training and awareness level (0-100)"
    ),
):
    """Perform quantum readiness assessment."""
    calc = QuantumReadinessCalculator(verbose=True)
    
    if sample:
        assessments = _add_sample_assessments()
        for org_name, params in assessments.items():
            result = calc.calculate_readiness_score(
                organization_name=org_name,
                **params
            )
            _display_readiness_summary(result)
            console.print()
    else:
        if not organization:
            organization = "Assessment Organization"
        
        # Use provided values or defaults
        crypto = crypto or 200
        migration = migration or 25.0
        detection = detection or 50
        compliance = compliance or 40
        training = training or 30
        
        with Progress() as progress:
            progress.add_task("Assessing readiness...", total=1)
            result = calc.calculate_readiness_score(
                organization_name=organization,
                crypto_inventory_level=crypto,
                migration_progress_percent=migration,
                detection_capability=detection,
                compliance_status=compliance,
                training_level=training,
            )
        
        _display_readiness_summary(result)


@app.command()
def overview(
    output: Optional[str] = typer.Option(
        None,
        "--output",
        help="Save visualization to file"
    ),
):
    """Generate readiness overview visualization."""
    console.print("[cyan]Generating readiness overview visualization...[/cyan]")
    
    calc = QuantumReadinessCalculator(verbose=True)
    result = calc.calculate_readiness_score(
        organization_name="Example Organization",
        crypto_inventory_level=280,
        migration_progress_percent=40,
        detection_capability=85,
        compliance_status=65,
        training_level=55,
    )
    
    output_path = output or "readiness_overview.png"
    calc.plot_readiness_overview(result, save_path=output_path)
    
    console.print(f"✓ Saved overview to {output_path}")


@app.command()
def gaps(
    output: Optional[str] = typer.Option(
        None,
        "--output",
        help="Save visualization to file"
    ),
):
    """Generate gap analysis visualization."""
    console.print("[cyan]Generating gap analysis visualization...[/cyan]")
    
    calc = QuantumReadinessCalculator(verbose=True)
    result = calc.calculate_readiness_score(
        organization_name="Example Organization",
        crypto_inventory_level=180,
        migration_progress_percent=20,
        detection_capability=60,
        compliance_status=40,
        training_level=30,
    )
    
    output_path = output or "gap_analysis.png"
    calc.plot_gap_analysis(result, save_path=output_path)
    
    console.print(f"✓ Saved gap analysis to {output_path}")


@app.command()
def progress(
    output: Optional[str] = typer.Option(
        None,
        "--output",
        help="Save visualization to file"
    ),
):
    """Generate progress trend visualization."""
    console.print("[cyan]Generating progress trend visualization...[/cyan]")
    
    calc = QuantumReadinessCalculator(verbose=True)
    
    # Simulate multiple assessments over time
    progress_scores = [
        (120, 10, 30, 25, 15),
        (180, 20, 50, 40, 30),
        (240, 35, 70, 55, 45),
        (300, 55, 95, 75, 65),
    ]
    
    for crypto, migration_pct, detect, comp, train in progress_scores:
        calc.calculate_readiness_score(
            organization_name="Example Organization",
            crypto_inventory_level=crypto,
            migration_progress_percent=migration_pct,
            detection_capability=detect,
            compliance_status=comp,
            training_level=train,
        )
    
    output_path = output or "progress_trend.png"
    calc.plot_progress_trend(save_path=output_path)
    
    console.print(f"✓ Saved progress trend to {output_path}")


@app.command()
def benchmark():
    """Display NIST readiness benchmarks."""
    console.print()
    
    benchmarks = [
        ("Developing", "0-250 points", "Initial phase, minimal quantum readiness", "⚠️"),
        ("Prepared", "251-500 points", "Basic readiness measures in place", "🟡"),
        ("Advanced", "501-750 points", "Significant progress on PQC migration", "🟢"),
        ("Leading", "751-1000 points", "Industry-leading quantum security posture", "✅"),
    ]
    
    table = Table(show_header=True, header_style="bold magenta", title="NIST Quantum Readiness Benchmarks")
    table.add_column("Level", style="cyan", width=15)
    table.add_column("Points", style="yellow", width=20)
    table.add_column("Description", style="white")
    table.add_column("", width=5)
    
    for level, points, description, icon in benchmarks:
        table.add_row(level, points, description, icon)
    
    console.print(table)
    
    console.print("\n[bold cyan]Scoring Factors:[/bold cyan]")
    
    factors_table = Table(show_header=True, header_style="bold magenta")
    factors_table.add_column("Factor", style="cyan")
    factors_table.add_column("Max Points", justify="right", style="yellow")
    factors_table.add_column("Description")
    
    factors = [
        ("Cryptography Inventory", "400", "Document and classify all cryptographic systems"),
        ("PQC Migration", "250", "Progress toward post-quantum cryptography adoption"),
        ("Threat Detection", "150", "Quantum threat monitoring and detection capabilities"),
        ("Regulatory Compliance", "100", "Alignment with NIST and other standards"),
        ("Training & Awareness", "100", "Security personnel competency and awareness"),
    ]
    
    for factor, points, description in factors:
        factors_table.add_row(factor, points, description)
    
    console.print(factors_table)
    console.print(f"\n[bold green]Total Possible: 1000 points[/bold green]")


@app.command()
def export(
    organization: str = typer.Option(
        "Example Org",
        "--organization",
        help="Organization name"
    ),
    format: str = typer.Option(
        "json",
        "--format",
        help="Export format (json, csv, pdf)"
    ),
    output: Optional[str] = typer.Option(
        None,
        "--output",
        help="Output file path"
    ),
):
    """Export readiness assessment report."""
    calc = QuantumReadinessCalculator(verbose=True)
    
    result = calc.calculate_readiness_score(
        organization_name=organization,
        crypto_inventory_level=280,
        migration_progress_percent=40,
        detection_capability=85,
        compliance_status=65,
        training_level=55,
    )
    
    if format.lower() == "json":
        output_path = output or f"{organization}_readiness.json"
        calc.export_readiness_json(result, output_path)
        console.print(f"✓ Exported to {output_path}")
    
    elif format.lower() == "csv":
        output_path = output or f"{organization}_readiness.csv"
        calc.export_readiness_csv(result, output_path)
        console.print(f"✓ Exported to {output_path}")
    
    elif format.lower() == "pdf":
        output_path = output or f"{organization}_readiness.pdf"
        try:
            calc.generate_pdf_report(result, output_path)
            console.print(f"✓ Exported to {output_path}")
        except ImportError:
            console.print("[red]✗ PDF export requires reportlab: pip install reportlab[/red]")
    
    else:
        console.print("[red]✗ Invalid format. Use: json, csv, or pdf[/red]")


@app.command()
def recommendations(
    crypto: int = typer.Option(
        200,
        "--crypto",
        help="Cryptography inventory score (0-400)"
    ),
    migration: float = typer.Option(
        25.0,
        "--migration",
        help="PQC migration progress percent (0-100)"
    ),
    detection: int = typer.Option(
        50,
        "--detection",
        help="Threat detection capability (0-150)"
    ),
    compliance: int = typer.Option(
        40,
        "--compliance",
        help="Regulatory compliance status (0-100)"
    ),
    training: int = typer.Option(
        30,
        "--training",
        help="Training and awareness level (0-100)"
    ),
):
    """Display readiness recommendations and action plan."""
    calc = QuantumReadinessCalculator(verbose=False)
    
    result = calc.calculate_readiness_score(
        organization_name="Assessment Organization",
        crypto_inventory_level=crypto,
        migration_progress_percent=migration,
        detection_capability=detection,
        compliance_status=compliance,
        training_level=training,
    )
    
    console.print()
    console.print("[bold cyan]Key Recommendations:[/bold cyan]")
    for i, rec in enumerate(result.recommendations, 1):
        console.print(f"{i}. {rec}")
    
    console.print("\n[bold cyan]Action Plan:[/bold cyan]")
    action_table = Table(show_header=True, header_style="bold magenta")
    action_table.add_column("Action", style="cyan")
    action_table.add_column("Timeline (Months)", justify="right", style="yellow")
    action_table.add_column("Priority", style="white")
    
    for action, months, priority in result.action_plan:
        priority_color = "red" if priority == "high" else "yellow" if priority == "medium" else "green"
        action_table.add_row(
            action,
            str(months),
            f"[{priority_color}]{priority.upper()}[/{priority_color}]"
        )
    
    console.print(action_table)
    
    console.print("\n[bold cyan]Gap Analysis Summary:[/bold cyan]")
    gap_table = Table(show_header=True, header_style="bold magenta")
    gap_table.add_column("Factor", style="cyan")
    gap_table.add_column("Gap %", justify="right")
    gap_table.add_column("Total Effort", justify="right", style="yellow")
    
    total_hours = 0
    for gap in result.gap_analysis:
        total_hours += gap.estimated_effort_hours
        gap_table.add_row(
            gap.factor,
            f"{gap.gap_percentage:.1f}%",
            f"{gap.estimated_effort_hours:.0f}h (~{gap.estimated_completion_months:.1f}m)"
        )
    
    console.print(gap_table)
    console.print(f"\n[bold]Total Estimated Effort: {total_hours:.0f} hours[/bold]")


if __name__ == "__main__":
    app()
