#!/usr/bin/env python3
# tests/phase-04/make_fixtures.py OUTDIR
# Emit MAAS (subnets/ipranges) + neutron (network/subnet) JSON fixtures mirroring the
# real schemas the phase-04 verify reads. The provider subnet uses id=7 (NOT 1) on
# purpose: it proves the script discovers BY CIDR, id-independently (PATTERN-1).
import json, os, sys

out = sys.argv[1]
os.makedirs(out, exist_ok=True)
def w(name, obj):
    with open(os.path.join(out, name), "w") as f:
        json.dump(obj, f, indent=2)

PROVIDER_ID = 7  # deliberately not 1

def subnet(i, cidr, gw, name):
    return {"id": i, "cidr": cidr, "gateway_ip": gw, "name": name,
            "vlan": {"id": 5000 + i, "vid": 0}}

# --- MAAS subnets ---
w("subnets-good.json", [
    subnet(PROVIDER_ID, "10.12.4.0/22", "10.12.4.1", "provider-public"),
    subnet(8,  "10.12.8.0/22",  "10.12.8.1",  "metal-admin"),
    subnet(10, "10.12.12.0/22", None,         "metal-internal"),
])
w("subnets-badgw.json", [
    subnet(PROVIDER_ID, "10.12.4.0/22", "10.12.4.254", "provider-public"),  # wrong gw
    subnet(8,  "10.12.8.0/22",  "10.12.8.1",  "metal-admin"),
])
w("subnets-noprovider.json", [
    subnet(8,  "10.12.8.0/22",  "10.12.8.1",  "metal-admin"),
    subnet(10, "10.12.12.0/22", None,         "metal-internal"),
])

def ipr(i, t, a, b, sid, comment=""):
    return {"id": i, "type": t, "start_ip": a, "end_ip": b,
            "comment": comment, "subnet": {"id": sid}}

# --- MAAS ipranges --- reserved FIP pool present (good) vs absent (nofip)
common = [
    ipr(1, "dynamic",  "10.12.9.0",   "10.12.11.254", 8,  "maas pxe/dhcp"),
    ipr(2, "reserved", "10.12.4.2",   "10.12.4.63",   PROVIDER_ID, "provider VIP /26"),
    ipr(4, "reserved", "10.12.8.2",   "10.12.8.63",   8,  "metal VIP /26"),
]
w("ipranges-good.json",  common + [
    ipr(3, "reserved", "10.12.5.0", "10.12.7.254", PROVIDER_ID, "FIP pool / ext_net (D-003)"),
])
w("ipranges-nofip.json", common)  # FIP pool reservation missing

# --- neutron network show -f json ---
w("net-good.json", {
    "name": "provider-ext", "router:external": True,
    "provider:network_type": "flat", "provider:physical_network": "physnet1",
    "shared": False, "tags": ["role=provider"],
})
w("net-bad-shared.json", {
    "name": "provider-ext", "router:external": True,
    "provider:network_type": "flat", "provider:physical_network": "physnet1",
    "shared": True, "tags": ["role=provider"],  # WRONG: shared breaks Option B
})

# --- neutron subnet show -f json --- two allocation_pools shapes (prove tolerance)
def sub(pools):
    return {"name": "provider-ext-fip", "cidr": "10.12.4.0/22",
            "gateway_ip": "10.12.4.1", "enable_dhcp": False,
            "allocation_pools": pools,
            "tags": ["role=provider", "netbox-iprange=10.12.5.0-10.12.7.254"]}
w("subnet-good-objpool.json", sub([{"start": "10.12.5.0", "end": "10.12.7.254"}]))
w("subnet-good-strpool.json", sub(["10.12.5.0-10.12.7.254"]))

print("fixtures written to", out)
