import typer
from typing import Optional, Annotated
from rich.table import Table
from rich.console import Console
from acemist.print_utils.print_network_templates import print_network_template_nets

app = typer.Typer(help="Manage networks within a Network Template.")





@app.command("add")
def add_network(
    ctx: typer.Context,
    template_id: str = typer.Argument(..., help="Network Template ID"),
    name: Optional[str] = typer.Option(None, help="Name of the Network"),
    subnet: Optional[str] = typer.Option(None, help="Subnet (CIDR)"),
    subnet6: Optional[str] = typer.Option(None, help="Subnet6 (CIDR), optional"),
    vlanid: Optional[str] = typer.Option(None, help="VlanId"),
):
    """Add a network to a Network Template."""
    # Required fields — prompt if not provided
    if name is None:
        name = typer.prompt("Network Name")
    if subnet is None:
        subnet = typer.prompt("Subnet")
    if vlanid is None:
        vlanid = typer.prompt("Vlan Id")

    # Optional fields — prompt with empty default so user can press Enter to skip
    if subnet6 is None:
        subnet6 = typer.prompt("Subnet6 (leave empty to skip)", default="") or None

    mist = ctx.obj.mist

    # Fetch network template
    template = mist.network_templates_get(template_id)

    # edit network template, add net
    new_net = {
        "vlan_id": vlanid,
        "subnet": subnet,
        "subnet6": subnet6
    }

    # Merge payload
    if name in template["networks"].keys():
        print("Network with same name exists in this template already! Exiting.")
        exit()

    else:
        template["networks"][name] = new_net

    # Confirm before add
    console = Console()
    console.print("Template networks after change: ")
    print_network_template_nets(template, highlighted_rows=[name])

    confirm = typer.confirm(f"Are you sure you want to add the network {name} to template {template["name"]}?")
    if not confirm:
        exit()

    # Put updated network template
    mist.network_templates_update(template_id, template)

@app.command("list")
def list_networks_vrf(
    ctx: typer.Context,
    template_id: str = typer.Argument(..., help="Network Template ID"),
    #site_id: str = typer.Argument(..., help="Site ID"),
):
    """List networks for a specific Network Template with VRF."""
    mist = ctx.obj.mist
    template = mist.network_templates_get(template_id)
    sites = mist.site_network_templates_get()
    networks = template.get("networks", [])
    
    def get_vrf(vrf_instances, network_name):
        for vrf, data in vrf_instances.items():
            if network_name in data.get("networks", []):
                return vrf
        return None

    network_names = [
        n["name"] if isinstance(n, dict) else n
        for n in networks
    ]

    for network_name in network_names:
        vrf = None

        for site_template in sites:
            vrf_instances = site_template.get("vrf_instances", {})
            vrf = get_vrf(vrf_instances, network_name)

            if vrf:
                template["networks"][network_name]["vrf"] = vrf
                
                break

        if not vrf:
            template["networks"][network_name]["vrf"] = "-"
            
    
    
    
    print_network_template_nets(template)