#!/usr/bin/env python3
"""Geometry sanity checks for the generated FirebaseOTA 3x6 Rev A carrier board.

Run after generate_easyeda.py.  The checks are deliberately conservative and
PRODUCTION-GRADE: they enforce IEC 60335-1 requirements without exceptions.

* pads of different nets: >= 0.20 mm
* pad to mounting/wall hole: >= 0.30 mm
* track to foreign pad: >= 0.50 mm
* track to hole: >= 1.00 mm (a metal M3 screw head is wider than the hole)
* track to track (different nets): >= 0.30 mm
* component body outlines must not overlap
* mains (AC_*) to SELV: >= 8 mm between ALL different footprints;
  NO same-component exemptions - the PCB must provide the primary barrier.
  If component-internal insulation is required, use a certified relay with
  reinforced insulation (4000 VAC) and refer to its datasheet.

The body outlines are duplicated from the generator on purpose: they are the
mechanical keep-outs, and a change there must be reviewed together with the
layout.

Mains nets: AC_L, AC_L_F, AC_N, plus any relay contact nets (NO, NC, COM
prefixed) and switched-load nets (L1..L4).
SELV nets: everything else (DevKit GPIOs, 5V_RAW/5V from HLK, GND, coil pins,
OLED I2C, PZEM, GPIO expansions).

This checker does NOT exempt same-relay pin pairs.  If you use a relay with
reinforced insulation (4000 VAC coil-to-contact per its datasheet), the
component provides the primary barrier, but the PCB creepage must still meet
the standard.  For full production certification, use a certified relay and
refer to its datasheet for the required creepage/clearance tables.
"""

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"}

# Relay contact nets are classified as mains (they switch high voltage)
# These are NOT exempt from the 8mm check in production-grade mode.
RELAY_MAINS_PREFIX = frozenset({"COM_", "NO_", "NC_"})
# Coil pins are SELV-driven but still require creepage distance
RELAY_COIL_PREFIX = frozenset({"Coil_"})

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 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 _is_mains_net(net: str) -> bool:
    """Return True if the net is classified as a mains circuit."""
    if net in MAINS:
        return True
    # Relay contact nets are also mains
    if any(net.startswith(prefix) for prefix in ("COM_", "NO_", "NC_")):
        return True
    # Switched-load nets are also mains
    if net.startswith("L"):
        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 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-relay exemptions
            # All different-net pad pairs must meet spacing requirements
            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})")

    # ------------------------------------------------------------------ mains to SELV pad check (≥8 mm, production grade)
    # SELV pads: all pads not classified as mains
    sel_pads = [p for p in pads if _is_sel_net(p["net"])]

    worst_pad = 1e9
    for m in pads:
        if not _is_mains_net(m["net"]):
            continue
        for s in sel_pads:
            # PRODUCTION GRADE: NO exemptions for same-relay pairs.
            # The PCB must provide the creepage barrier.
            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 (t for t in tracks if _is_mains_net(t["net"])):
        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 relay coil pads (SELV)
    worst_track2 = 1e9
    for t in (t for t in tracks if _is_mains_net(t["net"])):
        for p in pads:
            if p["net"].startswith("Coil_"):
                # No exemptions
                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_track2 = min(worst_track2, gap)
                if gap < 8.0:
                    fails.append(f"mains track-coil {gap:.2f} mm: {t['net']} / {p['net']}")
    print(f"min mains track to coil pad: {worst_track2:.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())