"""Programmatic libvirt network XML generation using xml.etree.ElementTree (D-06).

Builds NAT network XML without DHCP — cloud-init handles static IP assignment (D-03).
"""

from __future__ import annotations

import ipaddress
import xml.etree.ElementTree as ET

from vmcluster_mcp.topology.schema import NetworkSpec


def get_gateway_ip(subnet: str) -> str:
    """Return the gateway IP (first host address) for the given CIDR subnet."""
    net = ipaddress.IPv4Network(subnet, strict=False)
    return str(net.network_address + 1)


def build_network_xml(network: NetworkSpec) -> str:
    """Build a libvirt virtual network XML string for the given NetworkSpec.

    Creates an isolated NAT network. DHCP is intentionally omitted — per decision
    D-03, cloud-init NoCloud ISOs configure static IPs on each node.

    Args:
        network: Network specification with name, bridge, subnet.

    Returns:
        XML string suitable for conn.networkDefineXML().
    """
    net_obj = ipaddress.IPv4Network(network.subnet, strict=False)
    gateway_ip = get_gateway_ip(network.subnet)
    netmask = str(net_obj.netmask)

    root = ET.Element("network")

    ET.SubElement(root, "name").text = network.name
    ET.SubElement(root, "bridge", name=network.bridge, stp="on", delay="0")
    ET.SubElement(root, "forward", mode="nat")
    # Gateway IP element — no <dhcp> child (per D-03)
    ET.SubElement(root, "ip", address=gateway_ip, netmask=netmask)

    return ET.tostring(root, encoding="unicode")
