from rich.table import Table
from rich.console import Console
from rich import box
from datetime import datetime


def _fmt_time(ts):
    return datetime.fromtimestamp(ts).strftime("%Y-%m-%d") if ts else "-"


def print_list_network_templates(templates: list):
    console = Console()

    table = Table(box=box.ROUNDED, padding=(0, 1))
    table.add_column("Name", style="bold")
    table.add_column("Networks", justify="right")
    table.add_column("Port profiles", justify="right")
    table.add_column("Modified")
    table.add_column("ID", style="dim")

    for t in templates:
        networks = len(t.get("networks", {}))
        port_usages = len(t.get("port_usages", {}))
        table.add_row(
            t.get("name", "").strip(),
            str(networks) if networks else "-",
            str(port_usages) if port_usages else "-",
            _fmt_time(t.get("modified_time")),
            t.get("id", ""),
        )

    console.print(table)


def print_network_template_details(template: dict):
    console = Console()

    info = Table(box=box.ROUNDED, show_header=False, padding=(0, 1))
    info.add_column(style="bold cyan")
    info.add_column()

    info.add_row("Name", template.get('name'))
    info.add_row("Created", _fmt_time(template.get('created_time')))
    info.add_row("Modified", _fmt_time(template.get('modified_time')))
    info.add_row("Additional CMDs", str(len(template.get('additional_config_cmds'))))
    info.add_row("Networks", str(len(template.get('networks'))))
    info.add_row("VRFs", str(len(template.get('vrf_instances'))))
    info.add_row("Group Tags", str(len(template.get('group_tags'))))
    info.add_row("Import Org Nets", str(len(template.get('import_org_networks'))))
    console.print(info)


def print_network_template_nets(template: dict, highlighted_rows: list = []):

        console = Console()
        dim_others = bool(highlighted_rows)
        
        networks = template.get("networks", {})
        
        table = Table(
            title="Networks",
            box=box.ROUNDED,
            padding=(0, 1),
            show_lines=False,
        )

        table.add_column("Name", style="bold cyan", overflow="fold")
        table.add_column("VLAN", justify="right", style="magenta")
        table.add_column("Vrf", style="orange3")
        table.add_column("Subnet", style="green")
        table.add_column("Subnet6", style="green")

        for name, net in sorted(networks.items()):
            vlan = str(net.get("vlan_id", ""))
            subnet = net.get("subnet") or "-"
            subnet6 = net.get("subnet6") or "-"
            vrf = net.get("vrf") or "-"
            highlighted = name in highlighted_rows
            if highlighted:
                style = "bold green"
            elif dim_others:
                style = "dim"
            else:
                style = ""

            table.add_row(name, vlan, vrf,subnet, subnet6, style=style)
        
        console.print(table)