"""Rich console output for infra-diagram."""

from __future__ import annotations

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

from ..models import InfraDiagram

console = Console()


def render_diagram_info(diagram: InfraDiagram) -> None:
    """Render diagram information in the terminal."""
    console.print()
    console.print(
        Panel(
            f"[bold]infra-diagram[/] — Infrastructure Diagram Generator\n"
            f"[dim]Source:[/] {diagram.source_type.value}  "
            f"[dim]Components:[/] {diagram.node_count}  "
            f"[dim]Connections:[/] {diagram.edge_count}",
            style="bold blue",
            padding=(0, 2),
        )
    )

    if not diagram.nodes:
        console.print("[yellow]No infrastructure components found.[/]")
        return

    # Components table
    table = Table(
        title="[bold]Infrastructure Components[/]",
        box=box.ROUNDED,
        expand=True,
    )
    table.add_column("#", width=3, justify="right")
    table.add_column("", width=2)
    table.add_column("Name", ratio=1)
    table.add_column("Type", width=15)
    table.add_column("Provider", width=12)
    table.add_column("Source", width=20)

    for i, node in enumerate(diagram.nodes, 1):
        table.add_row(
            str(i),
            node.icon,
            node.name,
            node.node_type.value,
            node.provider,
            _truncate(node.source_file, 20),
        )

    console.print(table)

    # Connections table
    if diagram.edges:
        edge_table = Table(
            title="[bold]Connections[/]",
            box=box.ROUNDED,
            expand=True,
        )
        edge_table.add_column("From", ratio=1)
        edge_table.add_column("→", width=1)
        edge_table.add_column("To", ratio=1)
        edge_table.add_column("Relation", width=12)

        for edge in diagram.edges:
            src = diagram.get_node(edge.source)
            tgt = diagram.get_node(edge.target)
            if src and tgt:
                edge_table.add_row(
                    src.name,
                    "→",
                    tgt.name,
                    edge.label,
                )

        console.print(edge_table)

    # Groups
    if diagram.groups:
        console.print(f"\n  [bold]Groups:[/] {', '.join(g.name for g in diagram.groups)}")

    console.print()


def _truncate(text: str, max_len: int) -> str:
    if len(text) <= max_len:
        return text
    return "…" + text[-(max_len - 1):]
