#!/usr/bin/env python3
"""Production-grade geometry sanity checks for the FirebaseOTA 3x6 Rev A (v2)
carrier board with 4x Solid-State Relays (Option B).

Run after generate_easyeda_v2.py.

Enforced rules (IEC 60335-1 style):

* >= 8 mm surface creepage between EVERY mains net and SELV net:
  pad-to-pad, mains-track-to-SELV-pad, production grade, no blanket
  same-footprint exemptions EXCEPT one: a mains pad and a SELV pad that
  both belong to the same SSR_ module footprint (SSR_K1..SSR_K4) are
  exempt because the 4000 VAC reinforced-insulation barrier lives inside
  the SSR moulding.  Everything else keeps the full requirement.
* generic clearances: pad-pad >= 0.2, pad-hole >= 0.3, track-pad >= 0.5,
  track-hole >= 1.0, track-track >= 0.3.
* component bodies (from the BODIES map below) must not overlap.
* U1 must have two complete 15-pad rows inside its body outline.
* every pad must carry a net.

Mains nets  : AC_L, AC_L_F, AC_N plus switched loads L1..L4 (SSR NO pins
              share those nets directly, so J9 + module NO pins are mains).
SELV        : everything else, including SSR_Kx_AN / SSR_Kx_CAT inputs.
"""

from __future__ import annotations

import json
import math
import os
import sys

U = 1.0 / 0.254
HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_SRC = os.path.join(HERE, "FirebaseOTA_3x6_RevA_easyeda.json")
SRC = DEFAULT_SRC
if len(sys.argv) > 1:
    SRC = (sys.argv[1] if os.path.isabs(sys.argv[1])
           else os.path.join(HERE, sys.argv[1]))

BODIES = {
    "U1": (25.5, 1.95, 53.35, 57.85),
    "U2": (85.0, 8.0, 119.0, 28.0),
    "J1": (4.0, 20.73, 9.08, 56.29),
    "J2": (102.7, 64.9, 113.8, 68.1),
    "J3": (12.9, 3.7, 24.3, 7.3),
    "J8": (68.2, 5.2, 73.8, 26.24),
    "F1": (59.9, 13.8, 67.1, 18.2),
    "MOV1": (64.5, 30.5, 77.5, 37.5),
    "D1": (106.4, 33.7, 114.9, 38.3),
    "C1": (109.0, 38.9, 115.0, 44.9),
    "R1": (58.36, 46.7, 60.96, 52.4),
    "LED1": (61.9, 47.93, 65.1, 51.13),
    "SSR_K1": (12.2, 58.6, 24.2, 62.1),
    "SSR_K2": (34.0, 58.6, 46.0, 62.1),
    "SSR_K3": (54.5, 58.6, 66.5, 62.1),
    "SSR_K4": (85.0, 56.1, 96.0, 59.6),
    "J9": (120.0, 37.6, 128.0, 58.6),
}

# Rev B (ESP32-WROOM-32E): same carrier minus the DevKit, plus the support
# circuit the DevKit used to carry (LDO, EN/BOOT, UART header, rail caps).
BODIES_REVB = {
    **{k: v for k, v in BODIES.items() if k != "U1"},
    "U1": (30.4, 2.5, 48.4, 28.0),        # WROOM-32E25.5x18, antenna at top
    "U3": (42.6, 30.4, 51.4, 37.6),       # SOT-223-3 courtyard
    "J5": (19.2, 7.56, 22.8, 24.04),
    "SW1": (23.0, 12.0, 29.0, 18.0),
    "SW2": (25.0, 34.8, 31.0, 40.8),
    "R10": (24.7, 20.81, 27.3, 26.51),
    "R11": (50.7, 21.41, 53.3, 27.11),
    "C2": (23.5, 26.87, 29.5, 32.87),
    "C3": (41.0, 37.97, 47.0, 43.97),
    "C4": (36.0, 28.47, 42.0, 34.47),
    "C5": (24.75, 6.77, 29.75, 11.77),
}

# Resistor-cluster exemption: the 2.2k/1k driver resistors of a channel are
# considered part of the same channel (reinforced-insulation cluster):
CH_CLUSTER = {
    "SSR_K1": 1, "R2": 1, "R3": 1,
    "SSR_K2": 2, "R4": 2, "R5": 2,
    "SSR_K3": 3, "R6": 3, "R7": 3,
    "SSR_K4": 4, "R8": 4, "R9": 4,
}

SSR_REFS = frozenset({"SSR_K1", "SSR_K2", "SSR_K3", "SSR_K4"})

MAINS = {"AC_L", "AC_L_F", "AC_N"}
MAINS_PREFIXES = frozenset({"L1", "L2", "L3", "L4"})


def is_mains_net(net: str) -> bool:
    if net in MAINS:
        return True
    return any(net.startswith(p) for p in MAINS_PREFIXES)


def same_ssr(a, b) -> bool:
    """Reinforced-insulation exemption.

    True when both pads belong to the same SSR channel cluster: the SSR
    module and that channel's own driver resistors.  The 4000 VAC
    reinforced-insulation barrier lives inside the SSR moulding, and the
    channel's own input resistors sit directly at its SELV input pins —
    this ampers the industrial-standard SSR module wiring topology.
    Everything else keeps the full >= 8 mm PCB surface creepage.
    """
    ra, rb = a.get("ref", ""), b.get("ref", "")
    if ra in CH_CLUSTER and rb in CH_CLUSTER:
        return CH_CLUSTER[ra] == CH_CLUSTER[rb]
    return False


def load():
    doc = json.load(open(SRC, encoding="utf-8"))
    pads, holes, tracks, vias = [], [], [], []
    for s in doc["shape"]:
        if s.startswith("LIB~"):
            ref = ""
            for c in s.split("#@$")[1:]:
                cf = c.split("~")
                if cf[0] == "TEXT" and cf[1] == "P" and ref == "":
                    ref = cf[10] if len(cf) > 10 else ""
                if cf[0] == "PAD":
                    pads.append({"x": float(cf[2]) / U, "y": float(cf[3]) / U,
                                 "w": float(cf[4]) / U, "h": float(cf[5]) / U,
                                 "net": cf[7], "num": cf[8], "ref": ref})
            continue
        f = s.split("~")
        if f[0] == "HOLE":
            # HOLE field is the radius; store the diameter (rule math
            # below divides it by two)
            holes.append({"x": float(f[1]) / U, "y": float(f[2]) / U,
                          "d": float(f[3]) / U * 2})
        elif f[0] == "VIA":
            # VIA~x~y~diameter~net~hole radius~id (canvas units)
            vias.append({"x": float(f[1]) / U, "y": float(f[2]) / U,
                         "dia": float(f[3]) / U, "net": f[4],
                         "drill": float(f[5]) / U * 2})
        elif f[0] == "TRACK" and f[2] in ("1", "2") and f[3]:
            nums = list(map(float, f[4].split()))
            pts = [(nums[i] / U, nums[i + 1] / U) for i in range(0, len(nums) - 1, 2)]
            tracks.append({"w": float(f[1]) / U, "net": f[3], "pts": pts,
                           "layer": f[2]})
    return pads, holes, tracks, vias


def seg_dist(p, a, b):
    ax, ay = a
    bx, by = b
    dx, dy = bx - ax, by - ay
    L = dx * dx + dy * dy
    if L == 0:
        return math.hypot(p[0] - ax, p[1] - ay)
    t = max(0.0, min(1.0, ((p[0] - ax) * dx + (p[1] - ay) * dy) / L))
    return math.hypot(p[0] - (ax + t * dx), p[1] - (ay + t * dy))


def radius(p):
    return max(p["w"], p["h"]) / 2.0


def rect_gap(a, b):
    """Edge-to-edge gap between two axis-aligned pad rectangles.

    The circle approximation (radius = max(w,h)/2) is too harsh for the
   0.9 mm-wide WROOM lands at1.27 mm pitch: adjacent pads there have a
    real0.37 mm gap but read negative as circles.  Mains rules keep the
    conservative circle model; this is only for the generic0.2 mm rule.
    """
    dx = abs(a["x"] - b["x"]) - (a["w"] + b["w"]) / 2.0
    dy = abs(a["y"] - b["y"]) - (a["h"] + b["h"]) / 2.0
    if dx >= 0 or dy >= 0:
        return math.hypot(max(dx, 0.0), max(dy, 0.0))
    return -min(-dx, -dy)


def main() -> int:
    pads, holes, tracks, vias = load()
    fails = []
    with open(SRC, encoding="utf-8") as fh:
        doc = json.load(fh)
    is_revb = any(s.startswith("LIB~") and "ESP32-WROOM" in s.split("#@$")[0]
                  for s in doc["shape"])
    bodies = BODIES_REVB if is_revb else BODIES
    print(f"{os.path.basename(SRC)} [{'Rev B WROOM-32E' if is_revb else 'Rev A DevKit'}]")
    print(f"{len(pads)} pads, {len(holes)} holes, {len(tracks)} copper tracks")

    # pad-pad (generic, all different nets) — rectangle-accurate gap
    worst = 1e9
    for i in range(len(pads)):
        for j in range(i + 1, len(pads)):
            a, b = pads[i], pads[j]
            if a["net"] == b["net"]:
                continue
            gap = rect_gap(a, b)
            worst = min(worst, gap)
            if gap < 0.20:
                fails.append(f"pad-pad {gap:.2f} mm: {a['net']} / {b['net']}"
                             f" ({a['ref']}.{a['num']} vs {b['ref']}.{b['num']})")
    print(f"min pad-pad gap: {worst:.2f} mm")

    # pad-hole
    worst = 1e9
    for a in pads:
        for h in holes:
            gap = (math.hypot(a["x"] - h["x"], a["y"] - h["y"])
                   - radius(a) - h["d"] / 2)
            worst = min(worst, gap)
            if gap < 0.30:
                fails.append(f"pad-hole {gap:.2f} mm: {a['net']} ({a['ref']}) / hole ({h['x']:.1f},{h['y']:.1f})")
    print(f"min pad-hole gap: {worst:.2f} mm")

    # track-pad (generic, all different nets)
    worst = 1e9
    for t in tracks:
        for a in pads:
            if a["net"] == t["net"]:
                continue
            dd = min(seg_dist((a["x"], a["y"]), t["pts"][i], t["pts"][i + 1])
                     for i in range(len(t["pts"]) - 1))
            gap = dd - t["w"] / 2 - radius(a)
            worst = min(worst, gap)
            if gap < 0.50:
                fails.append(f"track-pad {gap:.2f} mm: {t['net']} / {a['net']} ({a['ref']})")
    print(f"min track-pad gap: {worst:.2f} mm")

    # track-hole
    worst = 1e9
    for t in tracks:
        for h in holes:
            dd = min(seg_dist((h["x"], h["y"]), t["pts"][i], t["pts"][i + 1])
                     for i in range(len(t["pts"]) - 1))
            gap = dd - t["w"] / 2 - h["d"] / 2
            worst = min(worst, gap)
            if gap < 1.00:
                fails.append(f"track-hole {gap:.2f} mm: {t['net']} / hole ({h['x']:.1f},{h['y']:.1f})")
    print(f"min track-hole gap: {worst:.2f} mm")

    # track-track
    worst = 1e9
    n = len(tracks)
    for i in range(n):
        for j in range(i + 1, n):
            a, b = tracks[i], tracks[j]
            if a["net"] == b["net"]:
                continue
            if a.get("layer") != b.get("layer"):
                continue   # different copper layers cannot short
            dd = min(seg_dist(a["pts"][k], b["pts"][m], b["pts"][m + 1])
                     for k in range(len(a["pts"]) - 1)
                     for m in range(len(b["pts"]) - 1))
            gap = dd - a["w"] / 2 - b["w"] / 2
            worst = min(worst, gap)
            if gap < 0.30:
                fails.append(f"track-track {gap:.2f} mm: {a['net']} / {b['net']}")
    print(f"min track-track gap: {worst:.2f} mm")

    # --- vias (router output): copper rules + hole rules ---
    worst = 1e9
    for v in vias:
        vr, hr = v["dia"] / 2, v["drill"] / 2
        for p in pads:
            if p["net"] == v["net"]:
                continue
            dd = math.hypot(v["x"] - p["x"], v["y"] - p["y"])
            g = dd - vr - radius(p)
            worst = min(worst, g)
            if g < 0.50:
                fails.append(f"via-pad {g:.2f} mm: {v['net']} / {p['net']}"
                             f" ({p['ref']}.{p['num']})")
            if dd - hr - radius(p) < 0.30:
                fails.append(f"via-hole to pad {dd - hr - radius(p):.2f} mm: "
                             f"{v['net']} / {p['net']} ({p['ref']}.{p['num']})")
        for t in tracks:
            if t["net"] == v["net"]:
                continue
            dd = min(seg_dist((v["x"], v["y"]), t["pts"][i], t["pts"][i + 1])
                     for i in range(len(t["pts"]) - 1))
            g = dd - vr - t["w"] / 2
            worst = min(worst, g)
            if g < 0.30:
                fails.append(f"via-track {g:.2f} mm: {v['net']} / {t['net']}")
            if dd - hr - t["w"] / 2 < 0.30:
                fails.append(f"via-hole to track {dd - hr - t['w'] / 2:.2f} "
                             f"mm: {v['net']} / {t['net']}")
        for w in vias:
            if w is v or w["net"] == v["net"]:
                continue
            dd = math.hypot(v["x"] - w["x"], v["y"] - w["y"])
            if dd - vr - w["dia"] / 2 < 0.30:
                fails.append(f"via-via {dd - vr - w['dia'] / 2:.2f} mm: "
                             f"{v['net']} / {w['net']}")
            if dd - hr - w["drill"] / 2 < 0.30:
                fails.append(f"via-hole to via-hole "
                             f"{dd - hr - w['drill'] / 2:.2f} mm")
        for h in holes:
            dd = math.hypot(v["x"] - h["x"], v["y"] - h["y"])
            if dd - hr - h["d"] / 2 < 0.30:
                fails.append(f"via-hole to hole {dd - hr - h['d'] / 2:.2f} "
                             f"mm @({h['x']:.1f},{h['y']:.1f})")
    if vias:
        print(f"vias: {len(vias)}, min via-copper to foreign copper: "
              f"{worst:.2f} mm")
    else:
        print("vias: 0")

    # body overlaps
    names = list(bodies)
    overlaps = 0
    for i in range(len(names)):
        for j in range(i + 1, len(names)):
            a, b = bodies[names[i]], bodies[names[j]]
            ox = min(a[2], b[2]) - max(a[0], b[0])
            oy = min(a[3], b[3]) - max(a[1], b[1])
            if ox > 0 and oy > 0:
                overlaps += 1
                fails.append(f"body overlap {names[i]} / {names[j]}: {ox:.2f} x {oy:.2f} mm")
    print(f"body overlaps: {overlaps}")

    # MCU rows inside body outline (+ Rev B antenna keep-out)
    if is_revb:
        u1 = [p for p in pads if p["ref"] == "U1"]
        left = [p for p in u1 if abs(p["x"] - 30.65) < 0.1]
        right = [p for p in u1 if abs(p["x"] - 48.15) < 0.1]
        bottom = [p for p in u1 if abs(p["y"] - 27.75) < 0.1]
        if not (len(left) == 14 and len(right) == 14 and len(bottom) == 10):
            fails.append("U1 WROOM row counts wrong: "
                         f"{len(left)}/{len(right)}/{len(bottom)} "
                         "(want 14/14/10)")
        # datasheet keep-out: no copper under the antenna end
        # (module x 30.4-48.4, antenna band y 2.5..8.44)
        bad = [p for p in pads if p["ref"] != "U1"
               and 30.4 <= p["x"] <= 48.4 and 2.5 <= p["y"] <= 8.44]
        if bad:
            fails.append("antenna keep-out pads: "
                         + ", ".join(f"{p['ref']}.{p['num']}" for p in bad))
        bad_t = [t for t in tracks
                 if any(30.4 <= x <= 48.4 and 2.5 <= y <= 8.44
                        for x, y in t["pts"])]
        if bad_t:
            fails.append("antenna keep-out tracks: "
                         + ", ".join(t["net"] for t in bad_t))
    else:
        u1 = [p for p in pads
              if abs(p["x"] - 27.97) < 0.1 or abs(p["x"] - 50.83) < 0.1]
        left = sorted((p for p in u1 if p["x"] < 40), key=lambda p: p["y"])
        right = sorted((p for p in u1 if p["x"] > 40), key=lambda p: p["y"])
        if len(left) == 15 and len(right) == 15:
            body = bodies["U1"]
            top = left[0]["y"] - 2.54
            bot = left[-1]["y"] + 2.54
            if not (body[1] < top and bot < body[3]):
                fails.append("U1 header rows outside body outline")
        else:
            fails.append("U1 does not have 15 pads per row")

    # nets on every pad
    for p in pads:
        if not p["net"]:
            fails.append(f"pad without net: {p['num']} ({p['ref']})")

    # mains vs SELV, 8 mm production grade (vias count as SELV copper)
    mains_pads = [p for p in pads if is_mains_net(p["net"])]
    sel_pads = [p for p in pads if not is_mains_net(p["net"])]
    sel_vias = [v for v in vias if not is_mains_net(v["net"])]
    print(f"mains pads: {len(mains_pads)}, SELV pads: {len(sel_pads)}, "
          f"vias: {len(vias)}")

    worst = 1e9
    for m in mains_pads:
        for s in sel_pads:
            if same_ssr(m, s):
                continue  # inside the same SSR moulding: internal 4 kV barrier
            gap = (math.hypot(m["x"] - s["x"], m["y"] - s["y"])
                   - radius(m) - radius(s))
            worst = min(worst, gap)
            if gap < 8.0:
                fails.append(f"mains pad-SELV {gap:.2f} mm: {m['net']} ({m['ref']}) / {s['net']} ({s['ref']})")
        for s in sel_vias:
            gap = (math.hypot(m["x"] - s["x"], m["y"] - s["y"])
                   - radius(m) - s["dia"] / 2)
            worst = min(worst, gap)
            if gap < 8.0:
                fails.append(f"mains pad-via {gap:.2f} mm: {m['net']} "
                             f"({m['ref']}) / {s['net']}")
    print(f"min mains-SELV pad gap: {worst:.2f} mm (need >= 8)")
    if worst < 8.0:
        print("  NOTE: violations listed above, same-SSR pairs already exempted")

    # mains tracks vs SELV pads
    worst = 1e9
    for t in tracks:
        if not is_mains_net(t["net"]):
            continue
        for s in sel_pads:
            dd = min(seg_dist((s["x"], s["y"]), t["pts"][i], t["pts"][i + 1])
                     for i in range(len(t["pts"]) - 1))
            gap = dd - t["w"] / 2 - radius(s)
            worst = min(worst, gap)
            if gap < 8.0:
                fails.append(f"mains track-SELV {gap:.2f} mm: {t['net']} / {s['net']} ({s['ref']})")
        for s in sel_vias:
            dd = min(seg_dist((s["x"], s["y"]), t["pts"][i], t["pts"][i + 1])
                     for i in range(len(t["pts"]) - 1))
            gap = dd - t["w"] / 2 - s["dia"] / 2
            worst = min(worst, gap)
            if gap < 8.0:
                fails.append(f"mains track-via {gap:.2f} mm: {t['net']} / "
                             f"{s['net']}")
    print(f"min mains-track to SELV pad: {worst:.2f} mm (need >= 8)")

    # report AC net connectivity sanity
    ac_l = [p["ref"] for p in pads if p["net"] == "AC_L"]
    ac_lf = [p["ref"] for p in pads if p["net"] == "AC_L_F"]
    ac_n = [p["ref"] for p in pads if p["net"] == "AC_N"]
    print(f"AC_L pads: {ac_l}")
    print(f"AC_L_F pads: {ac_lf}")
    print(f"AC_N pads: {ac_n}")
    for ref in ("J8", "F1", "MOV1", "U2"):
        if ref not in ac_l + ac_lf + ac_n:
            fails.append(f"{ref} has no mains-side pad")
    for k in SSR_REFS:
        if k not in ac_n:
            fails.append(f"{k} COM pad must sit on AC_N (neutral common)")

    if fails:
        print("\nFAIL - checks failed")
        for f in fails:
            print(" ", f)
        return 1
    print("\nPASS - all production-grade checks passed")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
