"""Rich display helpers."""
from __future__ import annotations

from typing import Any

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

console = Console()


def print_success(msg: str) -> None:
    console.print(f"[bold green]✓[/bold green] {msg}")


def print_error(msg: str) -> None:
    console.print(f"[bold red]✗[/bold red] {msg}")


def print_warning(msg: str) -> None:
    console.print(f"[bold yellow]![/bold yellow] {msg}")


def print_info(msg: str) -> None:
    console.print(f"[bold cyan]·[/bold cyan] {msg}")


def format_status_panel(status: dict[str, Any]) -> Panel:
    """Render RefreshWheel.status() as a Rich Panel."""
    lines: list[str] = []

    buf = status.get("buffer", {})
    lines.append(f"[bold]Buffer[/bold] ({buf.get('strategy', '?')})")
    lines.append(f"  Size: {buf.get('size', 0):,} / {buf.get('max_size', 0):,}  [{buf.get('fill_pct', 0):.1f}% full]")
    lines.append(f"  Total seen: {buf.get('total_seen', 0):,}")
    lines.append("")

    met = status.get("metrics", {})
    krs = met.get("krs", 100.0)
    krs_color = "green" if krs >= 80 else ("yellow" if krs >= 50 else "red")
    lines.append(f"[bold]Metrics[/bold]  (cycles: {met.get('cycles', 0)})")
    lines.append(f"  KRS:  [{krs_color}]{krs:.1f}[/{krs_color}] / 100")
    lines.append(f"  BWT:  {met.get('bwt', 0.0):.4f}")
    lines.append(f"  FWT:  {met.get('fwt', 0.0):.4f}")
    lines.append(f"  Rollbacks: {met.get('total_rollbacks', 0)}")
    lines.append("")

    last = status.get("last_refresh")
    if last:
        lines.append(f"[bold]Last refresh[/bold]  {last}")
    else:
        lines.append("[dim]No refresh cycles run yet.[/dim]")

    return Panel(
        Text.from_markup("\n".join(lines)),
        title="[bold]llm-refresh-wheel status[/bold]",
        border_style="cyan",
    )


def format_metrics_table(history: list[dict[str, Any]]) -> Table:
    """Render refresh history as a Rich Table."""
    table = Table(title="Refresh History", border_style="cyan")
    table.add_column("Cycle", style="dim")
    table.add_column("Timestamp")
    table.add_column("New", justify="right")
    table.add_column("Replay", justify="right")
    table.add_column("Pre-PPL", justify="right")
    table.add_column("Post-PPL", justify="right")
    table.add_column("BWT", justify="right")
    table.add_column("KRS", justify="right")
    table.add_column("Rolled", justify="center")

    for i, r in enumerate(history, 1):
        bwt = r.get("bwt", 0.0)
        krs = r.get("krs", 100.0)
        bwt_style = "red" if bwt < -0.05 else ("green" if bwt > 0 else "")
        krs_style = "green" if krs >= 80 else ("yellow" if krs >= 50 else "red")
        rolled = "[red]YES[/red]" if r.get("rolled_back") else "[green]no[/green]"
        pre = r.get("pre_eval") or {}
        post = r.get("post_eval") or {}
        ts = (r.get("timestamp", "")[:19]).replace("T", " ")
        table.add_row(
            str(r.get("cycle_id", i)),
            ts,
            str(r.get("new_examples", 0)),
            str(r.get("replay_examples", 0)),
            f"{pre.get('perplexity', 0.0):.2f}",
            f"{post.get('perplexity', 0.0):.2f}",
            f"[{bwt_style}]{bwt:.4f}[/{bwt_style}]" if bwt_style else f"{bwt:.4f}",
            f"[{krs_style}]{krs:.1f}[/{krs_style}]",
            rolled,
        )

    return table


def format_buffer_stats(stats: dict[str, Any]) -> Panel:
    lines = [f"[bold]Strategy:[/bold] {stats.get('strategy', '?')}"]
    for k, v in stats.items():
        if k == "strategy":
            continue
        lines.append(f"  {k}: {v}")
    return Panel("\n".join(lines), title="Buffer Stats", border_style="blue")
