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


def print_list_sites(sites: list):
    console = Console()

    table = Table(box=box.ROUNDED, padding=(0, 1))
    table.add_column("Name", style="bold")
    table.add_column("Address")
    table.add_column("Timezone", style="dim")
    table.add_column("ID", style="dim")

    for site in sites:
        table.add_row(
            site.get("name", ""),
            site.get("address", ""),
            site.get("timezone", ""),
            site.get("id", ""),
        )

    console.print(table)

def print_site_details(site: dict):
    from datetime import datetime

    console = Console()

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

    def fmt_val(v):
        if v is None:
            return "[dim]-[/dim]"
        return str(v)

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

    latlng = site.get("latlng", {})

    info.add_row("Name",          site.get("name", ""))
    info.add_row("ID",            site.get("id", ""))
    info.add_row("Org ID",        site.get("org_id", ""))
    info.add_row("Address",       site.get("address", ""))
    info.add_row("Country",       site.get("country_code", ""))
    info.add_row("Timezone",      site.get("timezone", ""))
    info.add_row("UTC offset",    str(site.get("tzoffset", "")))
    info.add_row("Lat/Lng",       f"{latlng.get('lat', '')}, {latlng.get('lng', '')}")
    info.add_row("Notes",         site.get("notes") or "-")
    info.add_row("Created",       fmt_time(site.get("created_time")))
    info.add_row("Modified",      fmt_time(site.get("modified_time")))

    console.print(info)

    templates = Table(title="Templates", box=box.ROUNDED, show_header=False, padding=(0, 1))
    templates.add_column(style="bold cyan", min_width=20)
    templates.add_column()

    for key in ("networktemplate_id", "gatewaytemplate_id", "routertemplate_id",
                "rftemplate_id", "aptemplate_id", "sitetemplate_id",
                "alarmtemplate_id", "secpolicy_id"):
        templates.add_row(key.replace("_", " ").title(), fmt_val(site.get(key)))

    console.print(templates)
