"""
Remediation command for generating detailed remediation reports.

This module implements the 'complio remediation' CLI command for
generating JSON reports with step-by-step remediation instructions.

Example:
    $ complio remediation scan_20260123_114704_tdrkba
    ✓ Remediation report generated: ~/.complio/reports/scan_20260123_114704_tdrkba_remediation.json
      Found 21 findings requiring remediation:
        • 1 Critical
        • 16 High
        • 2 Medium
        • 2 Low
"""

import click
from rich.console import Console

from complio.cli.output import ComplianceOutput
from complio.core.remediation import generate_remediation_report, load_scan_from_history
from complio.utils.logger import get_logger


@click.command()
@click.argument("scan_id", required=True)
@click.option(
    "--output",
    "-o",
    type=click.Path(),
    default=None,
    help="Custom output path for remediation JSON (optional)",
)
def remediation(scan_id: str, output: str = None) -> None:
    """Generate detailed remediation report from a scan.

    Reads scan results from history and generates a JSON file with
    comprehensive remediation instructions, including:

    - Step-by-step remediation procedures
    - AWS CLI commands
    - AWS Console navigation paths
    - Estimated remediation effort
    - Risk descriptions
    - ISO 27001 control mappings

    Arguments:

        SCAN_ID: The scan identifier (e.g., scan_20260123_114704_tdrkba)

    Examples:

        # Generate remediation report for a scan
        $ complio remediation scan_20260123_114704_tdrkba

        # Generate with custom output path
        $ complio remediation scan_20260123_114704_tdrkba --output /tmp/remediation.json

        # Output format:
        ✓ Remediation report generated: ~/.complio/reports/scan_xxx_remediation.json
          Found 21 findings requiring remediation:
            • 1 Critical
            • 16 High
            • 2 Medium
            • 2 Low
    """
    console = Console()
    output_helper = ComplianceOutput()
    logger = get_logger(__name__)

    try:
        # Load scan from history
        logger.info("loading_scan_from_history", scan_id=scan_id)
        console.print(f"[cyan]ℹ[/cyan] Loading scan: {scan_id}")

        try:
            results, region, account_id = load_scan_from_history(scan_id)
        except FileNotFoundError as e:
            output_helper.error(
                f"Scan '{scan_id}' not found",
                "Use 'complio history' to list available scans"
            )
            return
        except KeyError as e:
            # Better error message for missing keys in scan file
            output_helper.error(
                "Failed to load scan data",
                str(e)
            )
            return
        except ValueError as e:
            output_helper.error(
                "Failed to parse scan data",
                str(e)
            )
            return

        # Check if there are any findings
        total_findings = sum(len(tr.findings) for tr in results.test_results)

        if total_findings == 0:
            console.print(f"[green]✓[/green] No findings requiring remediation")
            logger.info("no_findings_to_remediate", scan_id=scan_id)
            return

        # Generate remediation report
        logger.info("generating_remediation_report", scan_id=scan_id, findings=total_findings)

        from pathlib import Path
        output_path = Path(output) if output else None

        report_path = generate_remediation_report(
            scan_id=scan_id,
            results=results,
            region=region,
            account_id=account_id,
            output_path=output_path
        )

        # Count findings by severity
        severity_counts = {"critical": 0, "high": 0, "medium": 0, "low": 0}
        for test_result in results.test_results:
            for finding in test_result.findings:
                if finding.severity in severity_counts:
                    severity_counts[finding.severity] += 1

        # Display success message
        console.print(f"[green]✓[/green] Remediation report generated: [cyan]{report_path}[/cyan]")
        console.print(f"  Found {total_findings} findings requiring remediation:")

        if severity_counts["critical"] > 0:
            console.print(f"    [red]• {severity_counts['critical']} Critical[/red]")
        if severity_counts["high"] > 0:
            console.print(f"    [orange1]• {severity_counts['high']} High[/orange1]")
        if severity_counts["medium"] > 0:
            console.print(f"    [yellow]• {severity_counts['medium']} Medium[/yellow]")
        if severity_counts["low"] > 0:
            console.print(f"    [blue]• {severity_counts['low']} Low[/blue]")

        logger.info("remediation_report_generated_successfully", path=str(report_path))

    except Exception as e:
        logger.error("remediation_command_failed", error=str(e), scan_id=scan_id)
        output_helper.error(
            "Failed to generate remediation report",
            str(e)
        )
        raise click.Abort()
