"""Rich startup banner and doctor report display for LLMHosts CLI."""

from __future__ import annotations

from typing import TYPE_CHECKING

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

if TYPE_CHECKING:
    from llmhosts.config import LLMHostsConfig
    from llmhosts.server import StartupReport

console = Console()

# ---------------------------------------------------------------------------
# Doctor check model
# ---------------------------------------------------------------------------


class DoctorCheck(BaseModel):
    """Result of a single ``llmhost doctor`` diagnostic check."""

    name: str
    status: str  # "ok", "warn", "fail"
    message: str
    suggestion: str | None = None


# ---------------------------------------------------------------------------
# Startup banner
# ---------------------------------------------------------------------------

_STATUS_ICONS = {
    True: "[green]✓[/green]",
    False: "[red]✗[/red]",
}


def print_banner(report: StartupReport, config: LLMHostsConfig) -> None:
    """Print the rich startup banner summarising what was discovered."""
    lines: list[str] = []

    # Header
    from llmhosts import __version__

    lines.append(f"[bold cyan]LLMHosts[/bold cyan] [dim]v{__version__}[/dim] — [italic]Your Personal AI Cloud[/italic]")
    lines.append("")

    # Endpoints
    base = f"http://{config.server.host}:{config.server.port}"
    lines.append(f"  [bold]Proxy:[/bold]      {base}")
    for ep in report.endpoints:
        lines.append(f"  [dim]{ep}[/dim]")
    lines.append("")

    # Inference engine
    icon = _STATUS_ICONS[report.ollama_available]
    if report.ollama_available:
        model_count = len(report.ollama_models)
        model_list = ", ".join(report.ollama_models[:3])
        if model_count > 3:
            model_list += f", ... (+{model_count - 3})"
        lines.append(f"  [bold]Inference:[/bold]  {icon} {model_count} model(s) ({model_list})")
    else:
        lines.append(f"  [bold]Inference:[/bold]  {icon} not reachable")

    # Cloud providers
    if report.cloud_providers:
        providers = ", ".join(report.cloud_providers)
        lines.append(f"  [bold]Cloud:[/bold]      {_STATUS_ICONS[True]} {providers}")
    else:
        lines.append("  [bold]Cloud:[/bold]      [dim]no BYOK keys configured[/dim]")

    # Hardware
    if report.hardware_summary:
        lines.append(f"  [bold]Hardware:[/bold]   {report.hardware_summary}")

    # Router / Cache tiers
    lines.append(f"  [bold]Router:[/bold]     {report.router_tier}")
    lines.append(f"  [bold]Cache:[/bold]      {report.cache_tier}")

    # Warnings
    if report.warnings:
        lines.append("")
        for w in report.warnings:
            lines.append(f"  [yellow]⚠ {w}[/yellow]")

    body = "\n".join(lines)
    panel = Panel(
        body,
        border_style="cyan",
        expand=False,
        padding=(1, 2),
    )
    console.print(panel)


# ---------------------------------------------------------------------------
# Doctor report
# ---------------------------------------------------------------------------

_DOCTOR_STYLES = {
    "ok": "[green]✓ PASS[/green]",
    "warn": "[yellow]⚠ WARN[/yellow]",
    "fail": "[red]✗ FAIL[/red]",
}


def print_doctor_report(results: list[DoctorCheck]) -> None:
    """Print a table of ``llmhost doctor`` check results."""
    from llmhosts import __version__

    console.print()
    console.print(f"[bold cyan]LLMHosts Doctor[/bold cyan] [dim]v{__version__}[/dim]")
    console.print()

    table = Table(show_header=True, header_style="bold", show_lines=False, expand=False)
    table.add_column("Check", style="bold", min_width=22)
    table.add_column("Status", justify="center", min_width=10)
    table.add_column("Details", min_width=40)

    for check in results:
        status_text = _DOCTOR_STYLES.get(check.status, check.status)
        detail = check.message
        if check.suggestion and check.status != "ok":
            detail += f"\n[dim]  → {check.suggestion}[/dim]"
        table.add_row(check.name, status_text, detail)

    console.print(table)

    # Summary
    ok_count = sum(1 for c in results if c.status == "ok")
    warn_count = sum(1 for c in results if c.status == "warn")
    fail_count = sum(1 for c in results if c.status == "fail")
    total = len(results)

    summary_parts: list[str] = []
    summary_parts.append(f"[green]{ok_count} passed[/green]")
    if warn_count:
        summary_parts.append(f"[yellow]{warn_count} warnings[/yellow]")
    if fail_count:
        summary_parts.append(f"[red]{fail_count} failed[/red]")
    summary_parts.append(f"[dim]{total} total[/dim]")

    console.print()
    console.print("  " + " · ".join(summary_parts))
    console.print()
