"""Rich display helpers for the AppXen CLI."""

from __future__ import annotations

from typing import Any

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

console = Console()
err_console = Console(stderr=True)


def error(message: str) -> None:
    err_console.print(f"[bold red]Error:[/bold red] {message}")


def success(message: str) -> None:
    console.print(f"[bold green]OK[/bold green] {message}")


def warn(message: str) -> None:
    console.print(f"[bold yellow]Warning:[/bold yellow] {message}")


def print_json(data: Any) -> None:
    """Print raw JSON for scripting."""
    import json

    console.print(json.dumps(data, indent=2))


def sources_table(sources: list[dict], total: int, offset: int) -> None:
    """Display sources as a Rich table."""
    table = Table(title=f"Sources ({total} total)")
    table.add_column("ID", style="dim", max_width=12)
    table.add_column("Filename", style="bold")
    table.add_column("Status")
    table.add_column("Chunks", justify="right")
    table.add_column("Created")

    for s in sources:
        status_style = {
            "ready": "green",
            "processing": "yellow",
            "queued": "blue",
            "failed": "red",
        }.get(s.get("status", ""), "dim")

        table.add_row(
            s.get("source_id", "")[:12],
            s.get("filename", ""),
            f"[{status_style}]{s.get('status', 'unknown')}[/{status_style}]",
            str(s.get("chunk_count", "")),
            s.get("created_at", "")[:19],
        )

    console.print(table)

    # Pagination hint
    end = offset + len(sources)
    if end < total:
        console.print(
            f"  Showing {offset + 1}–{end} of {total}. "
            f"Use [bold]--offset {end}[/bold] to see more.",
            style="dim",
        )


def search_results(results: list[dict]) -> None:
    """Display search results as Rich panels."""
    if not results:
        console.print("[dim]No results found.[/dim]")
        return

    for i, r in enumerate(results, 1):
        score = r.get("score", 0)
        filename = r.get("filename", "unknown")
        content = r.get("content", "").strip()
        chunk_id = r.get("chunk_id", "")[:12]

        panel = Panel(
            content[:500] + ("..." if len(content) > 500 else ""),
            title=f"[bold]#{i}[/bold] {filename} [dim](score: {score:.3f})[/dim]",
            subtitle=f"[dim]chunk: {chunk_id}[/dim]",
            border_style="blue",
        )
        console.print(panel)


def stats_panel(data: dict) -> None:
    """Display RAG stats as a Rich panel."""
    lines = [
        f"[bold]Sources:[/bold]  {data.get('source_count', 0)}",
        f"[bold]Chunks:[/bold]   {data.get('chunk_count', 0)}",
    ]
    if "storage_bytes" in data:
        mb = data["storage_bytes"] / (1024 * 1024)
        lines.append(f"[bold]Storage:[/bold]  {mb:.1f} MB")

    console.print(
        Panel("\n".join(lines), title="RAG Engine Stats", border_style="blue")
    )
