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

Run after generate_easyeda_SSR.py.  The checks enforce IEC 60335-1 requirements
with the following exemptions noted:

* The SSR (e.g., Crydom ODN2225) provides 4000 VAC reinforced insulation
  between input and output circuits as the primary barrier.
* The PCB must still provide >= 8 mm creepage between all different copper
  nets (input GPIO resistors vs. output COM/NO tracks) as a supplementary
  barrier, per the documented internal insulation.
* NO same-Component exemptions: every pad pair, track-to-track, and
  track-to-pad gap between a mains net and a SELV net must meet the >= 8 mm
  requirement on the PCB surface.

Mains nets: AC_L, AC_L_F, AC_N, plus any pad net prefixed with L1..L4
(switched load terminals from SSR NO outputs).

SELV nets: everything else (DevKit GPIOs, 5V_RAW/5V from HLK, GND, SSR input
nets (SSR_*_AN/SSR_*_CAT), OLED I2C, PZEM, GPIO expansions).

The checker does NOT exempt pairs of pads that belong to the same SSR
footprint (SSR_K1..SSR_K4).  Every pad pair, track-to-track, and track-to-pad
gap between a mains net and a SELV net must meet the >= 8 mm requirement.
"""

from __future__ import annotations

import json
import math
import os
from collections import defaultdict

U = 1.0 / 0.254
HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(HERE, "FirebaseOTA_3x6_RevA_easyeda.json")

MAINS = {"AC_L", "AC_L_F", "AC_N"}

# Nets that are classified as mains (switch high voltage)
MainsPrefix = frozenset({"L1", "L2", "L3", "L4"})  # SSR switched-load outputs


BODIES = {
    "U1": (25.5, 1.95, 53.35, 57.85),
    "U2": (78.0, 8.0, 112.0, 28.0),
    "J1": (5.27, 20.73, 10.35, 51.21),
    "J2": (8.7, 62.4, 20.2, 65.6),
    "J3": (108.7, 4.4, 120.2, 7.6),
    "J4": (60.7, 48.7, 63.3, 56.4),
    "J5": (68.7, 48.7, 71.3, 56.4),
    "J6": (60.7, 56.7, 63.3, 64.4),
    "J7": (68.7, 56.7, 71.3, 64.4),
    "J8": (58.0, 5.0, 68.0, 26.24),
    "F1": (68.7, 5.0, 77.3, 12.0),
    "MOV1": (57.0, 31.0, 68.5, 40.0),
    "D1": (112.8, 23.5, 120.3, 27.9),
    "C1": (120.8, 21.07, 127.2, 27.47),
    "R1": (68.7, 41.65, 71.3, 46.35),
    "LED1": (64.4, 42.4, 67.6, 45.6),
}


def load():
    doc = json.load(open(SRC, encoding="utf-8"))
    pads, holes, tracks = [], [], []
    for s in doc["shape"]:
        if s.startswith("LIB~"):
            for c in s.split("#@$")[1:]:
                f = c.split("~")
                if f[0] == "PAD":
                    pads.append(
                        {
                            "x": float(f[2]) / U,
                            "y": float(f[3]) / U,
                            "w": float(f[4]) / U,
                            "h": float(f[5]) / U,
                            "net": f[7],
                            "num": f[8],
                        }
                    )
            continue
        f = s.split("~")
        if f[0] == "HOLE":
            holes.append({"x": float(f[1]) / U, "y": float(f[2]) / U, "d": float(f[3]) / U})
        elif f[0] == "TRACK" and f[2] == "1" 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})
    return pads, holes, tracks


def is_mains_net(net: str) -> bool:
    """Return True if the net is classified as a mains circuit."""
    if net in MAINS:
        return True
    # SSR switched-load nets (L1..L4) are also mains
    if any(net.startswith(prefix) for prefix in MainsPrefix):
        return True
    return False


def is_sel_net(net: str) -> bool:
    """Return True if the net is SELV (not mains)."""
    return not is_mains_net(net)


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 main() -> int:
    pads, holes, tracks = load()
    fails: list[str] = []
    print(f"{len(pads)} pads, {len(holes)} holes, {len(tracks)} copper tracks")

    # ------------------------------------------------------------------ pad-pad
    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
            # PRODUCTION GRADE: No same-Component exemptions.
            # The PCB must provide >= 8mm creepage between all different nets.
            gap = (math.hypot(a["x"] - b["x"], a["y"] - b["y"])
                   - radius(a) - radius(b))
            worst = min(worst, gap)
            if gap < 0.20:
                fails.append(f"pad-pad {gap:.2f} mm: {a['net']} / {b['net']}")
    print(f"min pad-pad gap (production grade): {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']} at "
                    f"({a['x']:.1f},{a['y']:.1f}) / hole "
                    f"({h['x']:.1f},{h['y']:.1f})"
                )
    print(f"min pad-hole gap: {worst:.2f} mm")

    # ------------------------------------------------------------------ track-pad
    worst_pad = 1e9
    for t in tracks:
        for a in pads:
            if a["net"] == t["net"]:
                continue
            # PRODUCTION GRADE: No exemptions
            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_pad = min(worst_pad, gap)
            if gap < 0.50:
                fails.append(
                    f"track-pad {gap:.2f} mm: {t['net']} / {a['net']} at "
                    f"({a['x']:.1f},{a['y']:.1f})"
                )
    print(f"min track-pad gap (production grade): {worst_pad:.2f} mm")

    # ------------------------------------------------------------------ track-hole
    worst_hole = 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_hole = min(worst_hole, gap)
            if gap < 1.00:
                fails.append(
                    f"track-hole {gap:.2f} mm: {t['net']} / hole "
                    f"({h['x']:.1f},{h['y']:.1f})"
                )
    print(f"min track-hole gap: {worst_hole:.2f} mm")

    # ------------------------------------------------------------------ track-track
    worst = 1e9
    for i in range(len(tracks)):
        for j in range(i + 1, len(tracks)):
            a, b = tracks[i], tracks[j]
            if a["net"] == b["net"]:
                continue
            # PRODUCTION GRADE: No exemptions
            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 (production grade): {worst:.2f} mm")

    # ------------------------------------------------------------------ component bodies
    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]}: "
                             f"{ox:.2f} x {oy:.2f} mm")
    print(f"body overlaps: {overlaps}")

    # ------------------------------------------------------------------ DevKit header rows
    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
        print(f"U1 rows: y {left[0]['y']:.2f}..{left[-1]['y']:.2f}, "
              f"body {body[1]:.2f}..{body[3]:.2f}")
        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")

    # ------------------------------------------------------------------ every pad must have a net
    for p in pads:
        if not p["net"]:
            fails.append(f"pad without net: {p['num']} at ({p['x']:.1f},{p['y']:.1f})")

    # ------------------------------------------------------------------ every pad net classification
    for p in pads:
        p["ismains"] = is_mains_net(p["net"])

    mains_pads = [p for p in pads if p["ismains"]]
    sel_pads = [p for p in pads if not p["ismains"]]

    # ------------------------------------------------------------------ mains to SELV pad check (>=8 mm, production grade)
    # Note: SSR provides 4000 VAC internal insulation (primary barrier),
    # but PCB must still provide >= 8 mm creepage between all different nets.
    worst_pad = 1e9
    for m in mains_pads:
        for s in sel_pads:
            gap = (math.hypot(m["x"] - s["x"], m["y"] - s["y"])
                   - radius(m) - radius(s))
            worst_pad = min(worst_pad, gap)
            if gap < 8.0:
                fails.append(f"mains pad-SELV {gap:.2f} mm: {m['net']} / {s['net']}")
    print(f"min mains pad to SELV pad: {worst_pad:.2f} mm (need >= 8, production grade)")

    # ------------------------------------------------------------------ mains to SELV track check (>=8 mm, production grade)
    worst_track = 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)
            # NO exemptions - must be >= 8mm
            if gap < 8.0:
                fails.append(f"mains track-SELV {gap:.2f} mm: {t['net']} / {s['net']}")
    print(f"min mains track to SELV pad: {worst_track:.2f} mm (need >= 8, production grade)")

    # Also check mains tracks against SSR input pads (GPIO resistor nets)
    worst_track3 = 1e9
    for t in tracks:
        if not is_mains_net(t["net"]):
            continue
        for p in pads:
            if p["net"].startswith("SSR_") and "_AN" in p["net"]:
                # No exemptions - must be >= 8mm between mains tracks and
                # SSR input resistor copper
                dd = min(seg_dist((p["x"], p["y"]), t["pts"][i], t["pts"][i + 1])
                         for i in range(len(t["pts"]) - 1))
                gap = dd - t["w"] / 2 - radius(p)
                worst_track3 = min(worst_track3, gap)
                if gap < 8.0:
                    fails.append(f"mains track-SSR-input {gap:.2f} mm: {t['net']} / {p['net']}")
    print(f"min mains track to SSR input pad: {worst_track3:.2f} mm (need >= 8)")

    # ------------------------------------------------------------------ mains tracks against SSR output pads (COM/NO)
    worst_track4 = 1e9
    for t in tracks:
        if not is_mains_net(t["net"]):
            continue
        for p in pads:
            if p["net"].startswith("SSR_") and ("COM" in p["net"] or "NO" in p["net"]):
                # No exemptions - must be >= 8mm between mains tracks and
                # SSR output copper
                dd = min(seg_dist((p["x"], p["y"]), t["pts"][i], t["pts"][i + 1])
                         for i in range(len(t["pts"]) - 1))
                gap = dd - t["w"] / 2 - radius(p)
                worst_track4 = min(worst_track4, gap)
                if gap < 8.0:
                    fails.append(f"mains track-SSR-output {gap:.2f} mm: {t['net']} / {p['net']}")
    print(f"min mains track to SSR output pad: {worst_track4:.2f} mm (need >= 8)")

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


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