"""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:   "✗",
}

_CHECK_PASS_LABELS: dict[str, str] = {
    "asset_in_scope":            "Asset in scope",
    "finding_ineligible":        "Eligible finding",
    "required_sections_present": "Required sections present",
    "reproduction_quality":      "Reproduction steps",
    "impact_quality":            "Impact statement",
}

_CHECK_FAIL_LABELS: dict[str, str] = {
    "asset_in_scope":            "Asset not in scope",
    "finding_ineligible":        "Ineligible finding type",
    "required_sections_present": "Required sections missing",
    "reproduction_quality":      "No reproduction steps",
    "impact_quality":            "Weak impact statement",
}


def _check_label(check_id: str, passed: bool) -> str:
    if passed:
        return _CHECK_PASS_LABELS.get(check_id, check_id.replace("_", " ").title())
    return _CHECK_FAIL_LABELS.get(check_id, check_id.replace("_", " ").title())


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()
        if r.passed:
            console.print(f"  [green]✔[/green]  {_check_label(r.check_id, True)}")
            console.print(Padding(r.reason, pad=(0, 0, 0, 5)))
        else:
            console.print(f"  [red]✘[/red]  [red]{_check_label(r.check_id, False)}[/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]"
    )


