"""
Console output formatter for compliance scan results.

This module provides utilities to display scan results in a concise,
professional format using Rich for styling.

Example:
    >>> from complio.cli.formatters.console import display_scan_results
    >>> display_scan_results(results, scan_id, region, account_id, execution_time, pdf_path)
"""

from pathlib import Path
from typing import Optional

from rich.console import Console
from rich.panel import Panel
from rich.table import Table

from complio.core.runner import ScanResults
from complio.utils.aggregator import aggregate_findings, group_findings_by_severity


def mask_account_id(account_id: str) -> str:
    """Mask AWS Account ID to show only last 4 digits.

    Args:
        account_id: AWS account ID

    Returns:
        Masked account ID (e.g., ****7571)

    Example:
        >>> mask_account_id("631919637571")
        '****7571'
    """
    if not account_id or len(account_id) < 4:
        return account_id

    return f"****{account_id[-4:]}"


def display_scan_results(
    results: ScanResults,
    scan_id: str,
    region: str,
    account_id: str,
    execution_time: float,
    console: Optional[Console] = None,
) -> None:
    """Display scan results in concise, professional format.

    Args:
        results: Scan results to display
        scan_id: Unique scan identifier
        region: AWS region scanned
        account_id: AWS account ID (will be masked)
        execution_time: Execution time in seconds
        console: Optional Rich console (creates new one if None)

    Example:
        >>> display_scan_results(
        ...     results=scan_results,
        ...     scan_id="scan_20260122_172348_6g155r",
        ...     region="eu-west-3",
        ...     account_id="631919637571",
        ...     execution_time=12.1
        ... )
    """
    if console is None:
        console = Console()

    # Mask account ID
    masked_account = mask_account_id(account_id)

    # Aggregate findings
    aggregated = aggregate_findings(results)
    by_severity = group_findings_by_severity(aggregated)

    # Display header
    console.print()
    header_text = f"[bold]Complio Scan Results[/bold]\n[dim]Region: {region} • {execution_time:.1f}s[/dim]"
    console.print(Panel(header_text, border_style="cyan"))
    console.print()

    # Display overall score table
    score_table = Table(show_header=False, box=None, padding=(0, 2))
    score_table.add_column("Metric", style="cyan bold")
    score_table.add_column("Value", style="white bold")

    # Color code score
    score = results.overall_score
    if score >= 90:
        score_color = "green"
    elif score >= 70:
        score_color = "yellow"
    else:
        score_color = "red"

    score_table.add_row("Overall Score", f"[{score_color}]{score}%[/{score_color}]")
    score_table.add_row("Passed", f"[green]✅ {results.passed_tests}[/green]")
    score_table.add_row("Failed", f"[red]❌ {results.failed_tests}[/red]")
    if results.error_tests > 0:
        score_table.add_row("Errors", f"[yellow]⚠️  {results.error_tests}[/yellow]")

    console.print(score_table)
    console.print()

    # Display findings by severity
    severity_info = {
        "critical": ("🔴 CRITICAL", "red bold"),
        "high": ("🟠 HIGH", "orange1 bold"),
        "medium": ("🟡 MEDIUM", "yellow bold"),
        "low": ("🔵 LOW", "blue bold"),
    }

    for severity, (label, style) in severity_info.items():
        findings = by_severity.get(severity, [])
        if findings:
            console.print(f"[{style}]{label} ({len(findings)})[/{style}]")
            for finding in findings:
                # Format finding with resource count
                if finding.resource_count == 1:
                    console.print(f"   • {finding.title}")
                else:
                    console.print(f"   • {finding.title} — {finding.resource_count} {finding.resource_type}")
            console.print()

    # Display errors (tests that crashed)
    error_results = [r for r in results.test_results if r.status == "error"]
    if error_results:
        console.print("[yellow bold]⚠️  ERRORS ({0})[/yellow bold]".format(len(error_results)))
        for result in error_results:
            # Try to extract error message
            error_msg = "Unknown error"
            if result.findings and len(result.findings) > 0:
                error_msg = result.findings[0].title
            console.print(f"   • [dim]{result.test_id}:[/dim] {error_msg}")
        console.print()

    # Display footer with links
    console.print("─" * console.width)
    console.print(f"🔧 Remediation: [cyan]complio remediation {scan_id}[/cyan]")
    console.print(f"💡 Details: [dim]complio show <test_id>[/dim]")
    console.print(f"📋 Scan ID: [cyan]{scan_id}[/cyan]")
    console.print()


def display_connection_info(
    console: Console,
    account_id: str,
    region: str,
) -> None:
    """Display AWS connection information.

    Args:
        console: Rich console
        account_id: AWS account ID (will be masked)
        region: AWS region
    """
    masked_account = mask_account_id(account_id)
    console.print(f"[green]✓[/green] Connected to AWS Account: [cyan]{masked_account}[/cyan] ([cyan]{region}[/cyan])")


def display_progress_start(
    console: Console,
    total_tests: int,
) -> None:
    """Display progress start message.

    Args:
        console: Rich console
        total_tests: Total number of tests to run
    """
    console.print(f"[blue]⠸[/blue] Running {total_tests} compliance tests...")
