"""Format triage results into human-readable or JSON output."""

import json

from rich.console import Console
from rich.padding import Padding

from noisegate.models import ChecksResult, Verdict

_VERDICT_COLORS = {
    Verdict.PASS: "green",
    Verdict.WARN: "yellow",
    Verdict.FAIL: "bold red",
}

_VERDICT_ICONS = {
    Verdict.PASS: "✔",
    Verdict.WARN: "△",
    Verdict.FAIL: "✗",
}


_LABELS: dict[str, tuple[str, str]] = {
    "asset_in_scope": ("Asset in scope", "Asset not in scope"),
    "finding_ineligible": ("Eligible finding", "Ineligible finding type"),
    "impact_quality": ("Impact statement", "Weak impact statement"),
    "reproduction_quality": ("Reproduction steps", "No reproduction steps"),
    "required_sections_present": ("Required sections present", "Required sections missing"),
}


def _check_label(check_id: str, passed: bool) -> str:
    entry = _LABELS.get(check_id)
    if entry is None:
        return check_id.replace("_", " ").title()
    return entry[0] if passed else entry[1]


def render_json(result: ChecksResult) -> str:
    """Return a JSON string of the ChecksResult."""
    return json.dumps(result.model_dump(), indent=2)


def render_human(result: ChecksResult, console: Console | None = None) -> None:
    """Print a compact, human-readable triage result."""
    if console is None:
        console = Console()

    verdict = result.verdict
    color = _VERDICT_COLORS[verdict]
    icon = _VERDICT_ICONS[verdict]
    n_passed = sum(1 for r in result.checks if r.passed)

    console.print()
    console.print(
        f"[{color}]{icon}  {verdict.value}[/{color}]"
        f"  [dim]({n_passed}/{len(result.checks)} checks passed)[/dim]"
    )
    console.print()

    for i, r in enumerate(result.checks):
        if i > 0:
            console.print()
        label = _check_label(r.check_id, r.passed)
        if r.passed:
            console.print(f"  [green]✔[/green]  {label}")
            console.print(Padding(r.reason, pad=(0, 0, 0, 5)))
        else:
            console.print(f"  [red]✘[/red]  [red]{label}[/red]")
            console.print(Padding(r.reason, pad=(0, 0, 0, 5)))

    if result.summary:
        console.print()
        console.print(f"[bold]Summary:[/bold] {result.summary}")

    console.print()
    console.print(
        f"[dim]{result.model_used}"
        f"  ·  {result.prompt_tokens:,} in / {result.completion_tokens:,} out[/dim]"
    )
