#!/usr/bin/env python3
"""Offline stand-in for the VR1 apex. Binds 127.0.0.1:0 and prints the port on stdout
(two other agents share this jumphost -- a fixed port is a flaky-test generator).

Fixture rows mirror the state MEASURED live 2026-08-01 (docs/audit/d139-carve-dryrun-
20260801.txt). STUB_MODE: normal | no-role | conflict | empty-scope. Every non-GET is appended to
$STUB_WRITELOG -- the harness asserts that file stays EMPTY through a dry run.
"""
import json
import os
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

MODE = os.environ.get("STUB_MODE", "normal")
WRITELOG = os.environ.get("STUB_WRITELOG", "/dev/null")

SITES = [{"id": 8, "slug": "vr1-dc0", "name": "VR1 DC0"},
         {"id": 9, "slug": "vr1-dc1", "name": "VR1 DC1"}]
ROLES = [{"id": i, "slug": s} for i, s in enumerate(
    ["dc", "provider-public", "metal-admin", "metal-internal", "data-tenant",
     "storage", "replication", "lbaas-mgmt", "oob", "edge", "transit"], start=1)
    if not (MODE == "no-role" and s == "lbaas-mgmt")]


def row(cidr, dc, role, desc):
    site = next((s for s in SITES if s["slug"] == dc), None)
    return {"prefix": cidr, "status": {"value": "active"},
            "role": {"slug": role} if role else None,
            "scope": {"slug": site["slug"], "name": site["name"]} if site else None,
            "description": desc}


PREFIXES = [{"prefix": "fd50:840e:74e2::/48", "role": None, "scope": None,
             "description": "org ULA /48 -- an aggregate, NOT a VR1 plane"},
            {"prefix": "fd00::/8", "role": {"slug": "private"}, "scope": None,
             "description": "Unique Local Addresses (ULA)"}]
for dc, g, u in (("vr1-dc0", "2602:f3e2:f02", "fd50:840e:74e2:2"),
                 ("vr1-dc1", "2602:f3e2:f03", "fd50:840e:74e2:3")):
    n = dc[-1]
    PREFIXES.append(row("%s::/48" % g, dc, "dc", "VR1 Datacenter %s" % n))
    PREFIXES += [row("%s:10::/60" % g, dc, "provider-public", "VR1 DC%s provider-public (GUA /60; D-101/D-111)" % n),
                 row("%s:10::/64" % g, dc, "provider-public", "VR1 DC%s provider-public (GUA /64 active; D-101/D-111)" % n),
                 row("%s:11::/64" % g, dc, "provider-public", "VR1 DC%s provider-public (GUA VIP /64; D-101/D-111)" % n)]
    for nn, role in (("20", "metal-admin"), ("30", "data-tenant"),
                     ("40", "storage"), ("50", "replication")):
        PREFIXES.append(row("%s%s::/60" % (u, nn), dc, role, "VR1 DC%s %s (ULA /60; D-101/D-111)" % (n, role)))
        PREFIXES.append(row("%s%s::/64" % (u, nn), dc, role, "VR1 DC%s %s (ULA /64 active; D-101/D-111)" % (n, role)))
    PREFIXES.append(row("%s21::/64" % u, dc, "metal-internal", "VR1 DC%s metal-internal (ULA /64 active; D-101/D-111)" % n))
    v4 = "10.12.%d" % (4 if dc == "vr1-dc0" else 64)
    PREFIXES.append(row("%s.0/22" % v4, dc, "provider-public", "VR1 DC%s provider-public (v4; D-101)" % n))
    PREFIXES.append(row("172.30.%s.0/24" % (int(n) + 2), dc, "edge", "%s simulated-ISP edge WAN (D-115)" % dc))
    PREFIXES.append(row("172.31.0.%d/30" % (int(n) * 4), dc, "transit", "office1<->dc%s transit (D-124)" % n))
if MODE == "conflict":
    PREFIXES.append(row("2602:f3e2:f02:20::/64", "vr1-dc1", "storage", "mis-bound"))
if MODE == "empty-scope":
    # A FILTERED/failed read: rows come back, none for the asked DC. The site still
    # exists, so only the scoped-prefix count distinguishes this from a virgin DC.
    PREFIXES = [p for p in PREFIXES if (p.get("scope") or {}).get("slug") != "vr1-dc0"]

ADDRESSES = [{"address": "%s::%d/64" % (p, o), "description": "VIP"}
             for p in ("fd50:840e:74e2:220", "fd50:840e:74e2:221",
                       "fd50:840e:74e2:320", "fd50:840e:74e2:321",
                       "2602:f3e2:f02:11", "2602:f3e2:f03:11")
             for o in range(50, 63)] + [{"address": "10.10.1.10/24", "description": "netbox"}]
RANGES = [{"start_address": "10.12.4.4/22", "end_address": "10.12.4.49/22",
           "description": "D-134 utility band"}]

BODIES = {"/api/dcim/sites/": SITES, "/api/ipam/roles/": ROLES,
          "/api/ipam/prefixes/": PREFIXES, "/api/ipam/ip-addresses/": ADDRESSES,
          "/api/ipam/ip-ranges/": RANGES}


class H(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def _send(self, code, obj):
        b = json.dumps(obj).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(b)))
        self.end_headers()
        self.wfile.write(b)

    def do_GET(self):
        if self.headers.get("User-Agent") != "curl/8.5.0":
            return self._send(403, {"detail": "WAF: rejected User-Agent"})
        body = BODIES.get(self.path.split("?")[0])
        if body is None:
            return self._send(404, {"detail": "no such endpoint"})
        self._send(200, {"count": len(body), "next": None, "results": body})

    def _write(self):
        with open(WRITELOG, "a") as fh:
            fh.write("%s %s\n" % (self.command, self.path))
        self._send(201, {"id": 999})

    do_POST = do_PATCH = do_PUT = do_DELETE = _write


srv = HTTPServer(("127.0.0.1", 0), H)
sys.stdout.write("%d\n" % srv.server_address[1])
sys.stdout.flush()
srv.serve_forever()
