"""
CHRONOS CLI - Quantum Risk Calculator Commands
"""

import json
from datetime import datetime
from typing import Optional

import typer
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.bar import Bar

from chronos.core.analyze.risk_calculator import (
    QuantumRiskCalculator,
    DataAsset,
    DataAssetType,
    DataSensitivity,
    CryptographyType,
    MigrationScenario,
)

app = typer.Typer(name="risk", help="Quantum risk assessment and analysis")
console = Console()


@app.command("assess")
def assess_risk(
    config_file: Optional[str] = typer.Option(
        None, "--config", "-c", help="JSON config file with assets"
    ),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
):
    """
    Assess quantum computing threat to data assets.
    
    Example: chronos risk assess --config assets.json --verbose
    """
    console.print(
        Panel(
            "[bold]CHRONOS Quantum Risk Assessment[/bold]\n"
            "Monte Carlo simulation and Q-Day probability modeling",
            style="cyan"
        )
    )
    
    calc = QuantumRiskCalculator(verbose=verbose)
    
    if config_file:
        # Load assets from config
        try:
            with open(config_file) as f:
                config = json.load(f)
            
            for asset_cfg in config.get("assets", []):
                asset = DataAsset(
                    name=asset_cfg["name"],
                    asset_type=DataAssetType[asset_cfg["asset_type"]],
                    sensitivity=DataSensitivity[asset_cfg["sensitivity"]],
                    crypto_type=CryptographyType[asset_cfg["crypto_type"]],
                    key_size=asset_cfg["key_size"],
                    business_impact=asset_cfg.get("business_impact", 5),
                    metadata=asset_cfg.get("metadata", {}),
                )
                calc.add_asset(asset)
            
            console.print(f"[green]✓[/green] Loaded {len(calc.assets)} assets from config")
        
        except Exception as e:
            console.print(f"[red]Error loading config:[/red] {str(e)}", style="bold")
            raise typer.Exit(1)
    else:
        # Create sample assets for demonstration
        _add_sample_assets(calc)
    
    # Perform assessment
    console.print("\n[cyan]Assessing quantum threats...[/cyan]")
    assessments = calc.assess_all_assets()
    metrics = calc.get_risk_metrics()
    
    # Display results
    _display_assessment_results(assessments, metrics, calc)


@app.command("timeline")
def risk_timeline(
    output: Optional[str] = typer.Option(
        None, "--output", "-o", help="Save visualization to file"
    ),
    years: int = typer.Option(20, "--years", help="Timeline duration in years"),
):
    """
    Generate quantum threat evolution timeline visualization.
    
    Example: chronos risk timeline --output timeline.png --years 25
    """
    console.print(
        Panel(
            "[bold]Quantum Threat Timeline Visualization[/bold]\n"
            f"Projecting quantum risk over {years} years",
            style="cyan"
        )
    )
    
    calc = QuantumRiskCalculator()
    _add_sample_assets(calc)
    
    console.print("[cyan]Generating timeline visualization...[/cyan]")
    
    try:
        calc.plot_risk_timeline(
            filepath=output,
            show=not output,
            years=years,
        )
        
        if output:
            console.print(f"[green]✓[/green] Timeline saved to {output}")
        else:
            console.print("[green]✓[/green] Timeline displayed")
    
    except Exception as e:
        console.print(f"[red]Error generating timeline:[/red] {str(e)}", style="bold")
        raise typer.Exit(1)


@app.command("threats")
def threat_distribution(
    output: Optional[str] = typer.Option(
        None, "--output", "-o", help="Save visualization to file"
    ),
):
    """
    Visualize threat distribution across assets.
    
    Example: chronos risk threats --output threats.png
    """
    console.print(
        Panel(
            "[bold]Threat Distribution Analysis[/bold]\n"
            "Asset classification and urgency assessment",
            style="cyan"
        )
    )
    
    calc = QuantumRiskCalculator()
    _add_sample_assets(calc)
    
    console.print("[cyan]Analyzing threat distribution...[/cyan]")
    
    try:
        calc.plot_threat_distribution(
            filepath=output,
            show=not output,
        )
        
        if output:
            console.print(f"[green]✓[/green] Threat distribution saved to {output}")
        else:
            console.print("[green]✓[/green] Threat distribution displayed")
    
    except Exception as e:
        console.print(f"[red]Error visualizing threats:[/red] {str(e)}", style="bold")
        raise typer.Exit(1)


@app.command("roi")
def migration_roi(
    output: Optional[str] = typer.Option(
        None, "--output", "-o", help="Save visualization to file"
    ),
):
    """
    Compare ROI across migration scenarios.
    
    Example: chronos risk roi --output roi.png
    """
    console.print(
        Panel(
            "[bold]PQC Migration ROI Analysis[/bold]\n"
            "Cost-benefit analysis for migration scenarios",
            style="cyan"
        )
    )
    
    calc = QuantumRiskCalculator()
    _add_sample_assets(calc)
    
    # Create migration scenarios
    scenarios = [
        MigrationScenario(
            name="Early Adopter (2025)",
            migration_year=2025,
            pqc_algorithm="ML-KEM",
            cost_per_asset=7000,
            disruption_hours=6,
            success_probability=0.92,
        ),
        MigrationScenario(
            name="Standard (2026)",
            migration_year=2026,
            pqc_algorithm="ML-KEM",
            cost_per_asset=5000,
            disruption_hours=4,
            success_probability=0.95,
        ),
        MigrationScenario(
            name="Late Adopter (2027)",
            migration_year=2027,
            pqc_algorithm="ML-KEM",
            cost_per_asset=3500,
            disruption_hours=3,
            success_probability=0.97,
        ),
    ]
    
    console.print("[cyan]Analyzing migration scenarios...[/cyan]")
    
    try:
        calc.plot_migration_roi_comparison(
            scenarios,
            filepath=output,
            show=not output,
        )
        
        # Display ROI summary
        table = Table(title="Migration ROI Summary")
        table.add_column("Scenario", style="cyan")
        table.add_column("Total Cost", style="yellow")
        table.add_column("Benefit", style="green")
        table.add_column("ROI", style="magenta")
        
        for scenario in scenarios:
            roi = calc.calculate_migration_roi(scenario)
            table.add_row(
                scenario.name,
                f"${roi['total_cost']:,.0f}",
                f"${roi['expected_loss_avoided']:,.0f}",
                f"{roi['roi_percentage']:.1f}%",
            )
        
        console.print(table)
        
        if output:
            console.print(f"\n[green]✓[/green] ROI comparison saved to {output}")
        else:
            console.print("[green]✓[/green] ROI comparison displayed")
    
    except Exception as e:
        console.print(f"[red]Error analyzing ROI:[/red] {str(e)}", style="bold")
        raise typer.Exit(1)


@app.command("export")
def export_report(
    format: str = typer.Option(
        "json", "--format", "-f", help="Export format (json or csv)"
    ),
    output: str = typer.Option(
        None, "--output", "-o", help="Output file path"
    ),
):
    """
    Export risk assessment report.
    
    Example: chronos risk export --format json --output report.json
    """
    if not output:
        output = f"risk_report.{format}"
    
    console.print(
        Panel(
            f"[bold]Exporting Risk Report ({format.upper()})[/bold]\n"
            f"Output: {output}",
            style="cyan"
        )
    )
    
    calc = QuantumRiskCalculator()
    _add_sample_assets(calc)
    
    try:
        if format.lower() == "json":
            calc.export_risk_report_json(output)
        elif format.lower() == "csv":
            calc.export_risk_report_csv(output)
        else:
            console.print(f"[red]Unsupported format:[/red] {format}", style="bold")
            raise typer.Exit(1)
        
        console.print(f"[green]✓[/green] Report exported to {output}")
    
    except Exception as e:
        console.print(f"[red]Error exporting report:[/red] {str(e)}", style="bold")
        raise typer.Exit(1)


@app.command("decay")
def data_decay(
    output: Optional[str] = typer.Option(
        None, "--output", "-o", help="Save visualization to file"
    ),
):
    """
    Analyze data value decay over time.
    
    Example: chronos risk decay --output decay.png
    """
    console.print(
        Panel(
            "[bold]Data Value Decay Analysis[/bold]\n"
            "Sensitivity-based data depreciation over time",
            style="cyan"
        )
    )
    
    calc = QuantumRiskCalculator()
    _add_sample_assets(calc)
    
    # Create decay visualization
    import matplotlib.pyplot as plt
    from datetime import datetime
    
    fig, ax = plt.subplots(figsize=(12, 6))
    
    now = datetime.now().year
    
    for asset in calc.assets[:5]:  # Show first 5 assets
        decay = calc.calculate_data_value_decay(asset, retention_years=12)
        curve = decay.get_value_curve(now, now + 15, step=1)
        
        years = list(curve.keys())
        values = list(curve.values())
        
        ax.plot(
            years, values,
            marker="o",
            label=f"{asset.name} ({asset.sensitivity.value})",
            linewidth=2
        )
    
    ax.set_xlabel("Year", fontsize=12)
    ax.set_ylabel("Data Value", fontsize=12)
    ax.set_title("Data Value Decay by Sensitivity", fontsize=14, fontweight="bold")
    ax.grid(True, alpha=0.3)
    ax.legend(fontsize=10)
    
    plt.tight_layout()
    
    if output:
        plt.savefig(output, dpi=300, bbox_inches="tight")
        console.print(f"[green]✓[/green] Decay analysis saved to {output}")
    else:
        plt.show()
        console.print("[green]✓[/green] Decay analysis displayed")


def _add_sample_assets(calc: QuantumRiskCalculator) -> None:
    """Add sample assets for demonstration."""
    sample_assets = [
        DataAsset(
            name="Customer Database",
            asset_type=DataAssetType.DATABASE,
            sensitivity=DataSensitivity.RESTRICTED,
            crypto_type=CryptographyType.RSA,
            key_size=2048,
            business_impact=10,
            metadata={"data_lifetime": 20},
        ),
        DataAsset(
            name="SSL Certificates",
            asset_type=DataAssetType.CERTIFICATE,
            sensitivity=DataSensitivity.CONFIDENTIAL,
            crypto_type=CryptographyType.RSA,
            key_size=2048,
            business_impact=9,
            metadata={"data_lifetime": 5},
        ),
        DataAsset(
            name="API Keys Vault",
            asset_type=DataAssetType.VAULT,
            sensitivity=DataSensitivity.RESTRICTED,
            crypto_type=CryptographyType.AES,
            key_size=256,
            business_impact=8,
            metadata={"data_lifetime": 10},
        ),
        DataAsset(
            name="Historic Communications",
            asset_type=DataAssetType.COMMUNICATION,
            sensitivity=DataSensitivity.CONFIDENTIAL,
            crypto_type=CryptographyType.RSA,
            key_size=1024,  # Weak
            business_impact=6,
            metadata={"data_lifetime": 15},
        ),
        DataAsset(
            name="Identity Database",
            asset_type=DataAssetType.IDENTITY,
            sensitivity=DataSensitivity.RESTRICTED,
            crypto_type=CryptographyType.ECC,
            key_size=384,
            business_impact=10,
            metadata={"data_lifetime": 25},
        ),
        DataAsset(
            name="Archive Storage",
            asset_type=DataAssetType.FILE_STORAGE,
            sensitivity=DataSensitivity.INTERNAL,
            crypto_type=CryptographyType.AES,
            key_size=256,
            business_impact=3,
            metadata={"data_lifetime": 30},
        ),
        DataAsset(
            name="Web Content",
            asset_type=DataAssetType.FILE_STORAGE,
            sensitivity=DataSensitivity.PUBLIC,
            crypto_type=CryptographyType.RSA,
            key_size=2048,
            business_impact=2,
            metadata={"data_lifetime": 5},
        ),
        DataAsset(
            name="DH Key Exchanges",
            asset_type=DataAssetType.COMMUNICATION,
            sensitivity=DataSensitivity.CONFIDENTIAL,
            crypto_type=CryptographyType.DH,
            key_size=2048,
            business_impact=7,
            metadata={"data_lifetime": 8},
        ),
    ]
    
    calc.add_assets_batch(sample_assets)


def _display_assessment_results(
    assessments, metrics, calc: QuantumRiskCalculator
) -> None:
    """Display assessment results."""
    
    # Summary table
    table = Table(title="Risk Assessment Summary")
    table.add_column("Metric", style="cyan")
    table.add_column("Value", style="green")
    
    table.add_row(
        "Total Quantum Risk Score",
        f"{metrics.total_quantum_risk:.1f}/100",
    )
    table.add_row(
        "Critical Threat Assets",
        f"{metrics.critical_threat_assets}",
    )
    table.add_row(
        "Harvest-Now Vulnerable",
        f"{metrics.harvest_now_assets}",
    )
    table.add_row(
        "Average Urgency",
        f"{metrics.avg_urgency_score:.1f}/100",
    )
    table.add_row(
        "Timeline to Resilience",
        f"{metrics.timeline_to_resilience} years",
    )
    table.add_row(
        "Est. Migration Cost",
        f"${metrics.estimated_migration_cost:,.0f}",
    )
    table.add_row(
        "Resources Needed (FTE)",
        f"{metrics.resources_needed}",
    )
    
    console.print(table)
    
    # Detailed assessments
    console.print("\n[bold cyan]Asset Threat Assessments[/bold cyan]")
    
    detail_table = Table()
    detail_table.add_column("Asset", style="cyan")
    detail_table.add_column("Threat", style="yellow")
    detail_table.add_column("Urgency", style="magenta")
    detail_table.add_column("Harvest Risk", style="red")
    detail_table.add_column("Recommendation", style="green")
    
    for assessment in sorted(assessments, key=lambda a: a.urgency_score, reverse=True):
        threat_color = {
            "critical": "red",
            "high": "orange3",
            "medium": "yellow",
            "low": "green",
        }.get(assessment.threat_level, "white")
        
        detail_table.add_row(
            assessment.asset_name,
            f"[{threat_color}]{assessment.threat_level.upper()}[/{threat_color}]",
            f"{assessment.urgency_score:.1f}",
            f"{assessment.harvest_now_risk:.2f}",
            assessment.recommended_migration[:40],
        )
    
    console.print(detail_table)
    
    # Q-Day probabilities
    console.print("\n[bold cyan]Q-Day Emergence Probability[/bold cyan]")
    
    qday_table = Table()
    qday_table.add_column("Year", style="cyan")
    qday_table.add_column("Probability", style="yellow")
    qday_table.add_column("Visual", style="magenta")
    
    for year in [2030, 2035, 2040, 2045]:
        prob = calc.qday_model.get_probability_at_year(year)
        pct = int(prob * 100)
        bar = "█" * (pct // 5) + "░" * (20 - pct // 5)
        qday_table.add_row(str(year), f"{pct}%", bar)
    
    console.print(qday_table)


if __name__ == "__main__":
    app()
