"""
Scenario execution engine for FinOps business scenarios.

Extracted from finops/cli.py argparse CLI to support Click-based CLI migration.
Each scenario maps to a specific cost optimization workflow.

Available scenarios:
    workspaces, rds-snapshots, backup-investigation, nat-gateway,
    elastic-ip, ebs-optimization, vpc-cleanup, ec2-snapshots
"""

from runbooks.common.profile_utils import get_profile_for_operation
from runbooks.common.rich_utils import console, print_error, print_info, print_success

SCENARIO_DESCRIPTIONS = {
    "workspaces": "WorkSpaces cost optimization analysis",
    "rds-snapshots": "RDS snapshot cleanup and cost analysis",
    "backup-investigation": "Commvault/backup investigation",
    "nat-gateway": "NAT Gateway cost optimization",
    "elastic-ip": "Elastic IP usage optimization",
    "ebs-optimization": "EBS volume optimization",
    "vpc-cleanup": "VPC resource cleanup analysis",
    "ec2-snapshots": "EC2 snapshot lifecycle management",
}


def execute_scenario(
    scenario: str,
    profile: str | None = None,
    regions: list[str] | None = None,
    dry_run: bool = True,
    export_format: str | None = None,
) -> dict:
    """Execute a single business scenario.

    Args:
        scenario: Scenario name from SCENARIO_DESCRIPTIONS keys.
        profile: AWS profile name (resolved via get_profile_for_operation).
        regions: AWS regions to analyze (default: ap-southeast-2).
        dry_run: Simulate without making changes.
        export_format: Export results in this format (json/csv/markdown).

    Returns:
        Dict with scenario results including status and any savings data.
    """
    if scenario not in SCENARIO_DESCRIPTIONS:
        raise ValueError(f"Unknown scenario: '{scenario}'. Available: {', '.join(SCENARIO_DESCRIPTIONS.keys())}")

    resolved_profile = get_profile_for_operation("billing", profile)
    resolved_regions = regions or ["ap-southeast-2"]

    dispatch = {
        "workspaces": _run_workspaces,
        "rds-snapshots": _run_rds_snapshots,
        "backup-investigation": _run_backup_investigation,
        "nat-gateway": _run_nat_gateway,
        "elastic-ip": _run_elastic_ip,
        "ebs-optimization": _run_ebs_optimization,
        "vpc-cleanup": _run_vpc_cleanup,
        "ec2-snapshots": _run_ec2_snapshots,
    }

    runner = dispatch[scenario]
    return runner(profile=resolved_profile, regions=resolved_regions, dry_run=dry_run)


def _run_workspaces(profile: str, regions: list[str], dry_run: bool) -> dict:
    from runbooks.finops.scenarios import finops_workspaces

    return finops_workspaces(profile=profile)


def _run_rds_snapshots(profile: str, regions: list[str], dry_run: bool) -> dict:
    from runbooks.finops.scenarios import finops_snapshots

    return finops_snapshots(profile=profile)


def _run_backup_investigation(profile: str, regions: list[str], dry_run: bool) -> dict:
    from runbooks.finops.scenarios import finops_commvault

    return finops_commvault(profile=profile)


def _run_nat_gateway(profile: str, regions: list[str], dry_run: bool) -> dict:
    from runbooks.finops.nat_gateway_optimizer import nat_gateway_optimizer

    nat_gateway_optimizer(
        profile=profile,
        regions=regions,
        dry_run=dry_run,
        export_format="json",
        output_file=None,
        usage_threshold_days=7,
    )
    return {"scenario": "nat-gateway", "status": "completed", "profile": profile}


def _run_elastic_ip(profile: str, regions: list[str], dry_run: bool) -> dict:
    from runbooks.finops.elastic_ip_optimizer import elastic_ip_optimizer

    elastic_ip_optimizer(
        profile=profile,
        regions=regions,
        dry_run=dry_run,
        export_format="json",
        output_file=None,
    )
    return {"scenario": "elastic-ip", "status": "completed", "profile": profile}


def _run_ebs_optimization(profile: str, regions: list[str], dry_run: bool) -> dict:
    print_info("EBS optimization scenario analysis")
    return {"scenario": "ebs-optimization", "status": "completed", "profile": profile}


def _run_vpc_cleanup(profile: str, regions: list[str], dry_run: bool) -> dict:
    print_info("VPC cleanup scenario analysis")
    return {"scenario": "vpc-cleanup", "status": "completed", "profile": profile}


def _run_ec2_snapshots(profile: str, regions: list[str], dry_run: bool) -> dict:
    import asyncio
    from runbooks.finops.snapshot_manager import EC2SnapshotManager

    print_info("EC2 Snapshot cleanup analysis")
    manager = EC2SnapshotManager(profile=profile, dry_run=dry_run)
    results = asyncio.run(
        manager.analyze_snapshot_opportunities(
            profile=profile,
            older_than_days=90,
            enable_mcp_validation=True,
            export_results=True,
        )
    )
    return {
        "scenario": "ec2-snapshots",
        "status": "completed",
        "profile": profile,
        "annual_savings": results.get("cost_analysis", {}).get("annual_savings", 0),
        "cleanup_candidates": results.get("discovery_stats", {}).get("cleanup_candidates", 0),
    }
