"""Rich terminal output for assessment results."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

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

if TYPE_CHECKING:
    from rich.console import Console

    from complyform.core.assessor.control_matcher import Finding
    from complyform.reporting.json_report import AssessmentSummary

_STATUS_STYLE: dict[str, str] = {
    "PASS": "green",
    "FAIL": "red",
    "MANUAL_REVIEW": "yellow",
    "NOT_ASSESSED": "dim",
}
_SEVERITY_STYLE: dict[str, str] = {
    "CRITICAL": "red bold",
    "HIGH": "red",
    "MEDIUM": "yellow",
    "LOW": "blue",
}
_SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"]


def format_terminal_report(
    console: Console,
    findings: list[Finding],
    summary: AssessmentSummary,
    *,
    frameworks: list[str],
    cloud: str,
    resource_count: int,
    overlap_hints: list[dict[str, Any]] | None = None,
) -> None:
    """Render full assessment report to stderr console."""
    console.print(
        f"\n[bold]Assessment:[/bold] {', '.join(frameworks)} | {cloud}"
        f" | {resource_count} resources\n"
    )

    fail_and_pass = [f for f in findings if f.status in ("PASS", "FAIL")]
    if fail_and_pass:
        table = Table(title="Findings", show_lines=False)
        table.add_column("Severity", no_wrap=True)
        table.add_column("Control", style="cyan", no_wrap=True)
        table.add_column("Resource", style="white")
        table.add_column("Status", no_wrap=True)
        table.add_column("Finding")

        sorted_findings = sorted(
            fail_and_pass,
            key=lambda f: (
                _SEVERITY_ORDER.index(f.severity)
                if f.severity in _SEVERITY_ORDER
                else 99
            ),
        )

        for f in sorted_findings:
            sev_style = _SEVERITY_STYLE.get(f.severity, "")
            status_style = _STATUS_STYLE.get(f.status, "")
            table.add_row(
                f"[{sev_style}]{f.severity}[/{sev_style}]",
                f.control_id,
                f.resource_address,
                f"[{status_style}]{f.status}[/{status_style}]",
                f.finding[:80],
            )

        console.print(table)

    manual = [f for f in findings if f.status == "MANUAL_REVIEW"]
    if manual:
        console.print(
            f"\n[yellow]{len(manual)} controls require manual review[/yellow]"
        )

    not_assessed = [f for f in findings if f.status == "NOT_ASSESSED"]
    if not_assessed:
        console.print(
            f"\n[dim]{len(not_assessed)} resources not assessed"
            f" — run `complyform frameworks info {frameworks[0]}`"
            " for coverage details[/dim]"
        )

    score = summary.score
    if score >= 90:
        score_style = "green"
    elif score >= 70:
        score_style = "yellow"
    else:
        score_style = "red"

    summary_body = (
        f"[bold {score_style}]Score: {score}%[/bold {score_style}]\n\n"
        f"Passed: [green]{summary.passed}[/green] | "
        f"Failed: [red]{summary.failed}[/red] | "
        f"Manual: [yellow]{summary.manual_review}[/yellow] | "
        f"Not Assessed: [dim]{summary.not_assessed}[/dim]\n"
        f"Total Controls: {summary.total_controls}"
    )

    console.print(Panel(summary_body, title="Summary", style="cyan"))

    if overlap_hints:
        hint_lines = []
        for h in overlap_hints:
            hint_lines.append(
                f"  {h['framework']}: {h['overlap_pct']}% overlap"
                f" ({h['passing_shared']}/{h['shared_controls']} controls passing)"
            )
        console.print(
            Panel(
                "\n".join(hint_lines),
                title="Framework Overlap Opportunities",
                style="blue",
            )
        )

    if summary.failed > 0:
        console.print(
            "\n[dim]Run `complyform remediate --output=./patches`"
            " to generate fixes[/dim]"
        )
