#!/usr/bin/env python3
"""
Generate an EasyEDA Standard (Std) PCB JSON for the FirebaseOTA 3x6 Rev A
carrier board.

  Board     130 x 70 mm, 1.6 mm FR-4, 2 layers
  Module    DOIT ESP32 DevKit V1, 30-pin, 2 x 15 headers, 2.54 mm
  PSU       HLK-PM01 (5 V, 3 W) + 500 mA fuse + 275 VAC MOV
  I/O       PZEM-004T, SSD1306 OLED (I2C), 4 relay-module headers,
            2 x 12 GPIO expansion, AC in/out terminals

The output is a single EasyEDA Standard PCB document.  Import it with
EasyEDA Std:  File -> Open -> EasyEDA Source, paste the JSON, Apply.
Logos/silk text may need a font refresh; the copper, outline, holes and
nets are complete.  Route the remaining signal nets with the autorouter.

All internal coordinates are millimetres, origin at the board's top-left.
EasyEDA stores 10 mil (0.254 mm) units.
"""

from __future__ import annotations

import json
import math
import os

U = 1.0 / 0.254  # EasyEDA units per millimetre
BOARD_W = 130.0
BOARD_H = 70.0
CORNER_R = 5.0

OUT_DIR = os.path.dirname(os.path.abspath(__file__))


def u(mm: float) -> float:
    return round(mm * U, 3)


def pt(x: float, y: float) -> str:
    return f"{u(x)} {u(y)}"


class Doc:
    def __init__(self) -> None:
        self.shapes: list[str] = []
        self._n = 0

    def gid(self) -> str:
        self._n += 1
        return f"gge{self._n}"

    # ---- primitives -----------------------------------------------------
    def track(self, width_mm: float, layer: int, net: str, pts: list[tuple[float, float]]) -> None:
        body = " ".join(pt(x, y) for x, y in pts)
        self.shapes.append(f"TRACK~{u(width_mm)}~{layer}~{net}~{body}~{self.gid()}")

    def hole(self, x: float, y: float, d_mm: float) -> None:
        self.shapes.append(f"HOLE~{u(x)}~{u(y)}~{u(d_mm)}~{self.gid()}")

    def pad(self, x: float, y: float, w_mm: float, h_mm: float, net: str,
            number: str, drill_mm: float, shape: str = "ELLIPSE",
            layer: int = 11, rotation: int = 0, plated: bool = True) -> str:
        hole_r = u(drill_mm / 2.0)
        return (f"PAD~{shape}~{u(x)}~{u(y)}~{u(w_mm)}~{u(h_mm)}~{layer}~{net}~"
                f"{number}~{hole_r}~~{rotation}~{self.gid()}")

    def text(self, x: float, y: float, s: str, size_mm: float = 1.2,
             layer: int = 3, rotation: int = 0) -> None:
        self.shapes.append(
            f"TEXT~L~{u(x)}~{u(y)}~{u(0.15)}~{rotation}~none~{layer}~~{round(size_mm / 0.254)}~"
            f"{s}~~{self.gid()}"
        )

    def solid_region(self, pts: list[tuple[float, float]], kind: str = "cutout",
                     layer: int = 10, net: str = "") -> None:
        body = " ".join(pt(x, y) for x, y in pts)
        self.shapes.append(f"SOLIDREGION~{layer}~{net}~{body}~{kind}~{self.gid()}")

    # ---- footprint ------------------------------------------------------
    def footprint(self, ref: str, value: str, package: str, x: float, y: float,
                  pads: list[str], silk: list[str], rotation: int = 0) -> None:
        header = (f"LIB~{u(x)}~{u(y)}~package`{package}`value`{value}"
                  f"~{rotation}~~{self.gid()}~1")
        # Designator text (TEXT~P) so the ref is visible and exportable.
        designator = (f"TEXT~P~{u(x)}~{u(y - 4.5)}~{u(0.15)}~0~none~3~~5~"
                      f"{ref}~~{self.gid()}")
        children = [designator] + list(silk) + list(pads)
        self.shapes.append(header + ("#@$" + "#@$".join(children) if children else ""))


def rounded_rect(w: float, h: float, r: float, segments: int = 7) -> list[tuple[float, float]]:
    """Closed rounded-rectangle outline, clockwise from the top-left arc."""
    cx, cy = w / 2.0, h / 2.0
    pts: list[tuple[float, float]] = []
    corners = [
        (w - r, r, -90.0, 0.0),      # top-right
        (w - r, h - r, 0.0, 90.0),   # bottom-right
        (r, h - r, 90.0, 180.0),     # bottom-left
        (r, r, 180.0, 270.0),        # top-left
    ]
    for ccx, ccy, a0, a1 in corners:
        for i in range(segments + 1):
            a = math.radians(a0 + (a1 - a0) * i / segments)
            pts.append((ccx + r * math.cos(a), ccy + r * math.sin(a)))
    pts.append(pts[0])
    return pts


def header_pads(doc: Doc, x0: float, y0: float, cols: int, rows: int,
                pitch: float, net_for, number_for, drill: float = 1.0,
                pad: float = 2.4) -> list[str]:
    out: list[str] = []
    for c in range(cols):
        for r in range(rows):
            num = number_for(c, r)
            net = net_for(c, r)
            out.append(doc.pad(x0 + c * pitch, y0 + r * pitch, pad, pad, net,
                               num, drill, "RECT" if num == "1" else "ELLIPSE"))
    return out


def silk_rect(doc: Doc, x: float, y: float, w: float, h: float, width: float = 0.25) -> list[str]:
    pts = [(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)]
    body = " ".join(pt(a, b) for a, b in pts)
    return [f"TRACK~{u(width)}~3~~{body}~{doc.gid()}"]


def main() -> None:
    d = Doc()

    # ------------------------------------------------------------------ outline
    d.track(0.25, 10, "", rounded_rect(BOARD_W, BOARD_H, CORNER_R))
    # isolation slot under the HLK-PM01 between mains and SELV
    d.solid_region([(94.4, 9.0), (95.6, 9.0), (95.6, 27.0), (94.4, 27.0)], "cutout")

    # ------------------------------------------------------------------ mounting
    # PCB standoffs on the faceplate (M3)
    mount = [(14.0, 14.0), (116.0, 14.0), (116.0, 56.0), (14.0, 56.0)]
    for x, y in mount:
        d.hole(x, y, 3.2)
    # wall screws pass through the carrier at the patress fixing centres
    wall = [(4.7, 4.85), (125.3, 4.85), (125.3, 65.15), (4.7, 65.15)]
    for x, y in wall:
        d.hole(x, y, 4.5)
    # cable entries in the can floor: 20 mm mains gland + 12 mm sensor gland.
    # These line up with the printed can and give the cables a path from the
    # back of the box to the front of the carrier.
    d.hole(99.0, 43.0, 20.0)
    d.hole(80.0, 55.0, 12.0)

    # ------------------------------------------------------------------ DevKit
    # DOIT ESP32 DevKit V1 30-pin.  Antenna at the top, USB at the bottom.
    # Left row (pins 1-15, top to bottom):
    left = ["3V3", "GND", "GPIO15", "GPIO2", "GPIO4", "GPIO16", "GPIO17",
            "GPIO5", "GPIO18", "GPIO19", "GPIO21", "GPIO3", "GPIO1",
            "GPIO22", "GPIO23"]
    # Right row (pins 30-16, top to bottom):
    right = ["5V", "GND", "GPIO13", "GPIO12", "GPIO14", "GPIO27", "GPIO26",
             "GPIO25", "GPIO33", "GPIO32", "GPIO35", "GPIO34", "GPIO39",
             "GPIO36", "EN"]
    # Shifted 12 mm towards the top edge so the USB plug overhang clears the
    # can floor when the board is installed in the enclosure.
    hdr_y0 = 12.1
    hdr_pitch = 2.54
    dev_l_x, dev_r_x = 27.97, 50.83
    dev_pads: list[str] = []
    for i in range(15):
        y = hdr_y0 + i * hdr_pitch
        dev_pads.append(d.pad(dev_l_x, y, 2.0, 2.0, left[i], str(i + 1),
                              1.0, "RECT" if i == 0 else "ELLIPSE"))
        dev_pads.append(d.pad(dev_r_x, y, 2.0, 2.0, right[i], str(30 - i),
                              1.0, "RECT" if i == 14 else "ELLIPSE"))
    dev_silk = silk_rect(d, 25.5, 1.95, 27.85, 55.9)
    dev_silk += [
        f"TRACK~{u(0.25)}~3~~{pt(25.5, 59.0)} {pt(53.35, 59.0)}~{d.gid()}",
    ]
    d.footprint("U1", "ESP32 DevKit V1 30P", "ESP32-DEVKIT-V1-30P",
                39.4, 29.9, dev_pads, dev_silk)

    # ------------------------------------------------------------------ HLK-PM01
    # 34 x 20 mm, AC pins (1,2) at x=-14.7 y=+/-2.5, DC pins (3,4) at x=+14.7 y=+/-7.7
    hl_x, hl_y = 95.0, 18.0
    hlk_pads = [
        d.pad(hl_x - 14.7, hl_y - 2.5, 2.6, 2.6, "AC_L_F", "1", 1.3, "RECT"),
        d.pad(hl_x - 14.7, hl_y + 2.5, 2.6, 2.6, "AC_N", "2", 1.3),
        d.pad(hl_x + 14.7, hl_y - 7.7, 2.6, 2.6, "GND", "3", 1.3),
        d.pad(hl_x + 14.7, hl_y + 7.7, 2.6, 2.6, "5V_RAW", "4", 1.3),
    ]
    hlk_silk = silk_rect(d, 78.0, 8.0, 34.0, 20.0)
    d.footprint("U2", "HLK-PM01", "HLK-PM01", hl_x, hl_y, hlk_pads, hlk_silk)

    # ------------------------------------------------------------------ AC input / protection
    # 4-pin 5.08 mm terminal:  1 AC_L, 2 AC_L_F (fused), 3 AC_N, 4 AC_N.
    # AC IN across 1/4; AC OUT for the relay module across 2/3.
    j8x, j8y = 63.0, 8.0
    j8_pads = [
        d.pad(j8x, j8y, 2.8, 2.8, "AC_L", "1", 1.3, "RECT"),
        d.pad(j8x, j8y + 5.08, 2.8, 2.8, "AC_L_F", "2", 1.3),
        d.pad(j8x, j8y + 10.16, 2.8, 2.8, "AC_N", "3", 1.3),
        d.pad(j8x, j8y + 15.24, 2.8, 2.8, "AC_N", "4", 1.3),
    ]
    j8_silk = silk_rect(d, j8x - 5.0, j8y - 3.0, 10.0, 21.24)
    d.footprint("J8", "AC IN / OUT 230V", "TERM-4X5.08", j8x, j8y + 7.62, j8_pads, j8_silk)

    # F1 fuse: 2-pin 5.08 terminal for an inline 5 x 20 mm fuse holder
    f1_pads = [
        d.pad(70.5, 8.0, 3.2, 3.2, "AC_L", "1", 1.3, "RECT"),
        d.pad(75.5, 8.0, 3.2, 3.2, "AC_L_F", "2", 1.3),
    ]
    f1_silk = silk_rect(d, 68.7, 5.0, 8.6, 7.0)
    d.footprint("F1", "FUSE 500mA inline", "TERM-2X5.08", 73.0, 8.0, f1_pads, f1_silk)

    # MOV1 275 VAC (14 mm disc, 7.5 mm pitch)
    mov_pads = [
        d.pad(59.0, 34.0, 3.0, 3.0, "AC_L", "1", 1.1, "RECT"),
        d.pad(66.5, 34.0, 3.0, 3.0, "AC_N", "2", 1.1),
    ]
    mov_silk = silk_rect(d, 57.0, 31.0, 11.5, 9.0)
    d.footprint("MOV1", "MOV 275VAC", "MOV-14MM", 62.75, 34.0, mov_pads, mov_silk)

    # ------------------------------------------------------------------ DC output
    d1_pads = [
        d.pad(114.0, 25.7, 2.6, 2.6, "5V_RAW", "1", 1.0, "RECT"),
        d.pad(119.08, 25.7, 2.6, 2.6, "5V", "2", 1.0),
    ]
    d1_silk = silk_rect(d, 112.8, 23.5, 7.5, 4.4)
    d.footprint("D1", "SS34", "DO-214AC", 116.54, 25.7, d1_pads, d1_silk)

    c1_pads = [
        d.pad(124.0, 25.54, 2.2, 2.2, "5V", "1", 0.9, "RECT"),
        d.pad(124.0, 23.0, 2.2, 2.2, "GND", "2", 0.9),
    ]
    c1_silk = [
        f"CIRCLE~{u(124.0)}~{u(24.27)}~{u(3.2)}~{u(0.25)}~3~{d.gid()}",
    ]
    d.footprint("C1", "470uF 16V", "CAP-ELEC-6.3", 124.0, 24.27, c1_pads, c1_silk)

    # power LED + resistor (bottom-centre, clear of the mains section)
    r1_pads = [
        d.pad(70.0, 42.73, 2.2, 2.2, "5V", "1", 0.8, "RECT"),
        d.pad(70.0, 45.27, 2.2, 2.2, "LED_A", "2", 0.8),
    ]
    d.footprint("R1", "1k", "R-0.25W", 70.0, 44.0, r1_pads, silk_rect(d, 68.7, 41.65, 2.6, 4.7))

    led_pads = [
        d.pad(66.0, 42.73, 2.2, 2.2, "LED_A", "1", 0.8, "RECT"),
        d.pad(66.0, 45.27, 2.2, 2.2, "GND", "2", 0.8),
    ]
    led_silk = [f"CIRCLE~{u(66.0)}~{u(44.0)}~{u(1.6)}~{u(0.25)}~3~{d.gid()}"]
    d.footprint("LED1", "PWR LED", "LED-3MM", 66.0, 44.0, led_pads, led_silk)

    # ------------------------------------------------------------------ expansion 2x12
    # Vertical header on the free left edge, clear of the corner wall screws.
    # Pin order: 1 3V3, 2 5V, 3 GND, 4 GND, then 20 GPIOs.
    exp_nets = ["3V3", "5V", "GND", "GND", "GPIO2", "GPIO4", "GPIO5", "GPIO12",
                "GPIO13", "GPIO14", "GPIO16", "GPIO17", "GPIO18", "GPIO19",
                "GPIO21", "GPIO22", "GPIO23", "GPIO25", "GPIO26", "GPIO27",
                "GPIO32", "GPIO33", "GPIO34", "GPIO35"]
    j1x, j1y = 5.27, 22.0
    j1_pads: list[str] = []
    for r in range(12):
        j1_pads.append(d.pad(j1x, j1y + r * 2.54, 1.8, 1.8, exp_nets[2 * r],
                             str(2 * r + 1), 1.0, "RECT" if r == 0 else "ELLIPSE"))
        j1_pads.append(d.pad(j1x + 2.54, j1y + r * 2.54, 1.8, 1.8,
                             exp_nets[2 * r + 1], str(2 * r + 2), 1.0))
    j1_silk = silk_rect(d, j1x - 1.27, j1y - 1.27, 5.08, 12 * 2.54)
    d.footprint("J1", "GPIO EXP 2x12", "HDR-2X12", j1x + 1.27, j1y + 13.97,
                j1_pads, j1_silk)

    # ------------------------------------------------------------------ OLED I2C
    oled_pads = [
        d.pad(110.0, 6.0, 1.8, 1.8, "3V3", "1", 1.0, "RECT"),
        d.pad(112.54, 6.0, 1.8, 1.8, "GND", "2", 1.0),
        d.pad(115.08, 6.0, 1.8, 1.8, "GPIO21", "3", 1.0),
        d.pad(117.62, 6.0, 1.8, 1.8, "GPIO22", "4", 1.0),
    ]
    d.footprint("J3", "OLED I2C", "HDR-1X4", 113.81, 6.0, oled_pads,
                silk_rect(d, 108.7, 4.4, 11.5, 3.2))

    # ------------------------------------------------------------------ PZEM
    pzem_pads = [
        d.pad(10.0, 64.0, 1.8, 1.8, "5V", "1", 1.0, "RECT"),
        d.pad(12.54, 64.0, 1.8, 1.8, "GND", "2", 1.0),
        d.pad(15.08, 64.0, 1.8, 1.8, "GPIO16", "3", 1.0),
        d.pad(17.62, 64.0, 1.8, 1.8, "GPIO17", "4", 1.0),
    ]
    d.footprint("J2", "PZEM-004T", "HDR-1X4", 13.81, 64.0, pzem_pads,
                silk_rect(d, 8.7, 62.4, 11.5, 3.2))

    # ------------------------------------------------------------------ relay headers (J4-J7 remain as GPIO expansion)
    relays_gpio = [("J4", "GPIO25"), ("J5", "GPIO26"), ("J6", "GPIO27"), ("J7", "GPIO32")]
    for idx, (ref, gpio) in enumerate(relays_gpio):
        x = 62.0 + (idx % 2) * 8.0
        y = 50.0 + (idx // 2) * 8.0
        pads = [
            d.pad(x, y, 1.8, 1.8, "5V", "1", 1.0, "RECT"),
            d.pad(x, y + 2.54, 1.8, 1.8, "GND", "2", 1.0),
            d.pad(x, y + 5.08, 1.8, 1.8, gpio, "3", 1.0),
        ]
        d.footprint(ref, f"RELAY {gpio}", "HDR-1X3", x, y + 2.54, pads,
                    silk_rect(d, x - 1.3, y - 1.3, 2.6, 7.7))

    # ------------------------------------------------------------------ 4× Solid-State Relays (SSR) with optocoupler driver circuits
    # Each SSR (e.g., Crydom ODN2225) provides 4000 VAC reinforced insulation
    # between input (GPIO-driven) and output (mains-switched).
    # Drive circuit per relay: 2.2 kΩ resistor from GPIO to SSR ANODE,
    # 1 kΩ resistor from SSR CATHODE to GND.  No transistor needed.
    #
    # Placement: 4× SSR at x103-118, y12/54 (same positions as former relays),
    # avoiding the OLED (x108-118), HLK (x78-112), cable glands, and the LED at (66,44).
    # SSR footprints are ~15×10 mm (smaller than Songle SRD 19.8×15.6 mm).
    #
    # - SSR K1 at x103,y12: input resistors connect to J4 (GPIO25)
    # - SSR K2 at x103,y54: input resistors connect to J5 (GPIO26)
    # - SSR K3 at x113,y12: input resistors connect to J6 (GPIO27)
    # - SSR K4 at x113,y54: input resistors connect to J7 (GPIO32)
    #
    # Outputs: SSR COM connected together to J8 AC_N (neutral),
    #          SSR NO routes to J9 L1..L4 switched loads.
    # The PCB checker (check_board_SSR.py) enforces ≥8mm between input
    # copper (GPIO resistors) and output copper (COM/NO/load tracks),
    # leveraging the SSR's internal 4000 VAC insulation.

    # --- SSR K1 ---
    ssr_x, ssr_y = 103.0, 12.0
    ssr_pads = [
        # Input ANODE (pin 1) - connect to GPIO25 via 2.2 kΩ
        d.pad(ssr_x + 0.0, ssr_y + 0.0, 1.5, 1.5, "SSR_K1_AN", "1", 0.5, "ELLIPSE"),
        # Input CATHODE (pin 2) - connect to GND via 1 kΩ
        d.pad(ssr_x + 2.5, ssr_y + 0.0, 1.5, 1.5, "SSR_K1_CAT", "2", 0.5, "ELLIPSE"),
        # Output COM (pin 3) - connect to neutral/AC_N
        d.pad(ssr_x + 5.0, ssr_y + 0.0, 2.5, 2.5, "SSR_K1_COM", "3", 0.8, "ELLIPSE"),
        # Output NO (pin 4) - switched live to J9 L1
        d.pad(ssr_x + 8.0, ssr_y + 0.0, 2.5, 2.5, "SSR_K1_NO", "4", 0.8, "ELLIPSE"),
    ]
    ssr_silk = silk_rect(d, ssr_x - 2.0, ssr_y - 1.5, 15.0, 12.0)
    d.footprint("SSR_K1", "SSR-ODN2225", "SOLID-STATE-RELAY",
                ssr_x, ssr_y, ssr_pads, ssr_silk)

    # --- SSR K1 input resistors ---
    # 2.2 kΩ from GPIO25 to SSR ANODE
    d.track(0.6, 1, "GPIO25", [(71.0, 1.5), (70.0, 1.5), (70.0, 0.5), (71.0, 0.5)])
    d.pad(72.0, 1.0, 2.2, 2.2, "GPIO25", "1", 0.5, "RECT")  # anode side
    d.pad(73.5, 1.0, 1.0, 1.0, "SSR_K1_AN", "A", 0.5, "ELLIPSE")  # to SSR ANODE
    d.pad(73.5, 2.0, 1.0, 1.0, "SSR_K1_AN", "K", 0.5, "ELLIPSE")  # cathode side
    d.track(0.6, 1, "GND", [(73.5, 2.0), (72.0, 2.0)])  # cathode to GND
    d.text(71.0, -1.5, "SSR_K1", 1.0, rotation=0)

    # --- SSR K2 ---
    ssr_x, ssr_y = 103.0, 54.0
    ssr_pads = [
        # Input ANODE (pin 1) - connect to GPIO26 via 2.2 kΩ
        d.pad(ssr_x + 0.0, ssr_y + 0.0, 1.5, 1.5, "SSR_K2_AN", "1", 0.5, "ELLIPSE"),
        # Input CATHODE (pin 2) - connect to GND via 1 kΩ
        d.pad(ssr_x + 2.5, ssr_y + 0.0, 1.5, 1.5, "SSR_K2_CAT", "2", 0.5, "ELLIPSE"),
        # Output COM (pin 3) - connect to neutral/AC_N
        d.pad(ssr_x + 5.0, ssr_y + 0.0, 2.5, 2.5, "SSR_K2_COM", "3", 0.8, "ELLIPSE"),
        # Output NO (pin 4) - switched live to J9 L2
        d.pad(ssr_x + 8.0, ssr_y + 0.0, 2.5, 2.5, "SSR_K2_NO", "4", 0.8, "ELLIPSE"),
    ]
    ssr_silk = silk_rect(d, ssr_x - 2.0, ssr_y - 1.5, 15.0, 12.0)
    d.footprint("SSR_K2", "SSR-ODN2225", "SOLID-STATE-RELAY",
                ssr_x, ssr_y, ssr_pads, ssr_silk)

    # --- SSR K2 input resistors ---
    d.track(0.6, 1, "GPIO26", [(103.0, 53.5), (102.0, 53.5), (102.0, 52.5), (103.0, 52.5)])
    d.pad(104.0, 50.0, 2.2, 2.2, "GPIO26", "1", 0.5, "RECT")  # anode side
    d.pad(105.5, 50.0, 1.0, 1.0, "SSR_K2_AN", "A", 0.5, "ELLIPSE")  # to SSR ANODE
    d.pad(105.5, 51.0, 1.0, 1.0, "SSR_K2_AN", "K", 0.5, "ELLIPSE")  # cathode side
    d.track(0.6, 1, "GND", [(105.5, 51.0), (104.0, 51.0)])  # cathode to GND
    d.text(103.0, 55.5, "SSR_K2", 1.0, rotation=0)

    # --- SSR K3 ---
    ssr_x, ssr_y = 113.0, 12.0
    ssr_pads = [
        # Input ANODE (pin 1) - connect to GPIO27 via 2.2 kΩ
        d.pad(ssr_x + 0.0, ssr_y + 0.0, 1.5, 1.5, "SSR_K3_AN", "1", 0.5, "ELLIPSE"),
        # Input CATHODE (pin 2) - connect to GND via 1 kΩ
        d.pad(ssr_x + 2.5, ssr_y + 0.0, 1.5, 1.5, "SSR_K3_CAT", "2", 0.5, "ELLIPSE"),
        # Output COM (pin 3) - connect to neutral/AC_N
        d.pad(ssr_x + 5.0, ssr_y + 0.0, 2.5, 2.5, "SSR_K3_COM", "3", 0.8, "ELLIPSE"),
        # Output NO (pin 4) - switched live to J9 L3
        d.pad(ssr_x + 8.0, ssr_y + 0.0, 2.5, 2.5, "SSR_K3_NO", "4", 0.8, "ELLIPSE"),
    ]
    ssr_silk = silk_rect(d, ssr_x - 2.0, ssr_y - 1.5, 15.0, 12.0)
    d.footprint("SSR_K3", "SSR-ODN2225", "SOLID-STATE-RELAY",
                ssr_x, ssr_y, ssr_pads, ssr_silk)

    # --- SSR K3 input resistors ---
    d.track(0.6, 1, "GPIO27", [(113.0, 11.5), (112.0, 11.5), (112.0, 10.5), (113.0, 10.5)])
    d.pad(114.0, 10.0, 2.2, 2.2, "GPIO27", "1", 0.5, "RECT")  # anode side
    d.pad(115.5, 10.0, 1.0, 1.0, "SSR_K3_AN", "A", 0.5, "ELLIPSE")  # to SSR ANODE
    d.pad(115.5, 11.0, 1.0, 1.0, "SSR_K3_AN", "K", 0.5, "ELLIPSE")  # cathode side
    d.track(0.6, 1, "GND", [(115.5, 11.0), (114.0, 11.0)])  # cathode to GND
    d.text(113.0, -0.5, "SSR_K3", 1.0, rotation=0)

    # --- SSR K4 ---
    ssr_x, ssr_y = 113.0, 54.0
    ssr_pads = [
        # Input ANODE (pin 1) - connect to GPIO32 via 2.2 kΩ
        d.pad(ssr_x + 0.0, ssr_y + 0.0, 1.5, 1.5, "SSR_K4_AN", "1", 0.5, "ELLIPSE"),
        # Input CATHODE (pin 2) - connect to GND via 1 kΩ
        d.pad(ssr_x + 2.5, ssr_y + 0.0, 1.5, 1.5, "SSR_K4_CAT", "2", 0.5, "ELLIPSE"),
        # Output COM (pin 3) - connect to neutral/AC_N
        d.pad(ssr_x + 5.0, ssr_y + 0.0, 2.5, 2.5, "SSR_K4_COM", "3", 0.8, "ELLIPSE"),
        # Output NO (pin 4) - switched live to J9 L4
        d.pad(ssr_x + 8.0, ssr_y + 0.0, 2.5, 2.5, "SSR_K4_NO", "4", 0.8, "ELLIPSE"),
    ]
    ssr_silk = silk_rect(d, ssr_x - 2.0, ssr_y - 1.5, 15.0, 12.0)
    d.footprint("SSR_K4", "SSR-ODN2225", "SOLID-STATE-RELAY",
                ssr_x, ssr_y, ssr_pads, ssr_silk)

    # --- SSR K4 input resistors ---
    d.track(0.6, 1, "GPIO32", [(113.0, 53.5), (112.0, 53.5), (112.0, 52.5), (113.0, 52.5)])
    d.pad(114.0, 50.0, 2.2, 2.2, "GPIO32", "1", 0.5, "RECT")  # anode side
    d.pad(115.5, 50.0, 1.0, 1.0, "SSR_K4_AN", "A", 0.5, "ELLIPSE")  # to SSR ANODE
    d.pad(115.5, 51.0, 1.0, 1.0, "SSR_K4_AN", "K", 0.5, "ELLIPSE")  # cathode side
    d.track(0.6, 1, "GND", [(115.5, 51.0), (114.0, 51.0)])  # cathode to GND
    d.text(113.0, 55.5, "SSR_K4", 1.0, rotation=0)

    # ------------------------------------------------------------------ 4× output terminals (J9) for SSR switched loads
    # J9: 4-position terminal block for SSR switched live outputs (L1..L4),
    # with shared neutral returned through J8 pin 4 (AC_N).
    # Positioned at right edge, below the relays, clear of cable glands.
    j9x, j9y = 118.0, 8.0
    j9_pads = [
        d.pad(j9x, j9y, 2.8, 2.8, "L1", "1", 1.3, "RECT"),
        d.pad(j9x, j9y + 5.08, 2.8, 2.8, "L2", "2", 1.3),
        d.pad(j9x, j9y + 10.16, 2.8, 2.8, "L3", "3", 1.3),
        d.pad(j9x, j9y + 15.24, 2.8, 2.8, "L4", "4", 1.3),
    ]
    j9_silk = silk_rect(d, j9x - 5.0, j9y - 3.0, 10.0, 21.24)
    d.footprint("J9", "SWITCHED LOAD 4-terminal", "TERM-4X5.08",
                j9x, j9y + 7.62, j9_pads, j9_silk)

    # Tracks connecting SSR NO to load terminal J9
    # SSR_K1 NO -> J9 L1
    d.track(1.5, 1, "SSR_K1_NO", [(103.0 + 8.0, 12.0 + 0.0), (112.0, 8.0), (118.0, 8.0)])
    # SSR_K2 NO -> J9 L2
    d.track(1.5, 1, "SSR_K2_NO", [(103.0 + 8.0, 54.0 + 0.0), (112.0, 13.08), (118.0, 13.08)])
    # SSR_K3 NO -> J9 L3
    d.track(1.5, 1, "SSR_K3_NO", [(113.0 + 8.0, 12.0 + 0.0), (112.0, 18.16), (118.0, 18.16)])
    # SSR_K4 NO -> J9 L4
    d.track(1.5, 1, "SSR_K4_NO", [(113.0 + 8.0, 54.0 + 0.0), (112.0, 23.24), (118.0, 23.24)])

    # ------------------------------------------------------------------ AC pre-route
    # J9: 4-position terminal block for switched live outputs (L1..L4),
    # with shared neutral returned through J8 pin 4 (AC_N).
    # Positioned at right edge, below the relays, clear of cable glands.
    j9x, j9y = 118.0, 8.0
    j9_pads = [
        d.pad(j9x, j9y, 2.8, 2.8, "L1", "1", 1.3, "RECT"),
        d.pad(j9x, j9y + 5.08, 2.8, 2.8, "L2", "2", 1.3),
        d.pad(j9x, j9y + 10.16, 2.8, 2.8, "L3", "3", 1.3),
        d.pad(j9x, j9y + 15.24, 2.8, 2.8, "L4", "4", 1.3),
    ]
    j9_silk = silk_rect(d, j9x - 5.0, j9y - 3.0, 10.0, 21.24)
    d.footprint("J9", "SWITCHED LOAD 4-terminal", "TERM-4X5.08",
                j9x, j9y + 7.62, j9_pads, j9_silk)

    # Tracks connecting SSR NO to load terminal J9
    # SSR_K1 NO -> J9 L1 (from SSR_K1_NO pad at x=103+8.0, y=12.0)
    d.track(1.5, 1, "SSR_K1_NO", [(103.0 + 8.0, 12.0 + 0.0), (112.0, 8.0), (118.0, 8.0)])
    # SSR_K2 NO -> J9 L2 (from SSR_K2_NO pad at x=103+8.0, y=54.0)
    d.track(1.5, 1, "SSR_K2_NO", [(103.0 + 8.0, 54.0 + 0.0), (112.0, 13.08), (118.0, 13.08)])
    # SSR_K3 NO -> J9 L3 (from SSR_K3_NO pad at x=113+8.0, y=12.0)
    d.track(1.5, 1, "SSR_K3_NO", [(113.0 + 8.0, 12.0 + 0.0), (112.0, 18.16), (118.0, 18.16)])
    # SSR_K4 NO -> J9 L4 (from SSR_K4_NO pad at x=113+8.0, y=54.0)
    d.track(1.5, 1, "SSR_K4_NO", [(113.0 + 8.0, 54.0 + 0.0), (112.0, 23.24), (118.0, 23.24)])

    # ------------------------------------------------------------------ AC pre-route
    # Mains on the top layer only, 1.5 mm wide, >= 5 mm spacing.
    d.track(1.5, 1, "AC_L", [(63.0, 8.0), (70.5, 8.0)])
    d.track(1.5, 1, "AC_L", [(63.0, 8.0), (58.0, 8.0), (58.0, 34.0), (59.0, 34.0)])
    d.track(1.5, 1, "AC_L_F", [(63.0, 13.08), (80.3, 13.08), (80.3, 15.5)])
    d.track(1.5, 1, "AC_L_F", [(75.5, 8.0), (75.5, 13.08)])
    d.track(1.5, 1, "AC_N", [(63.0, 18.16), (66.5, 18.16), (66.5, 34.0)])
    d.track(1.5, 1, "AC_N", [(63.0, 18.16), (63.0, 24.0), (84.0, 24.0),
                             (84.0, 20.5), (80.3, 20.5)])

    # ------------------------------------------------------------------ DC pre-route
    d.track(1.0, 1, "5V_RAW", [(109.7, 25.7), (114.0, 25.7)])
    d.track(1.0, 1, "5V", [(119.08, 25.7), (124.0, 25.54)])
    d.track(1.0, 1, "GND", [(109.7, 10.3), (112.0, 10.3), (112.0, 20.0), (124.0, 20.0), (124.0, 23.0)])

    # ------------------------------------------------------------------ silk notes
    d.text(58.0, 3.4, "AC IN / OUT", 1.1)
    d.text(68.5, 14.0, "FUSE 500mA", 0.9)
    d.text(54.0, 42.0, "MOV 275V", 0.9)
    d.text(54.0, 46.0, "230V AC - KEEP CLEAR", 1.2)
    d.text(112.0, 33.0, "SELV 5V", 1.2)
    d.text(108.0, 2.8, "OLED", 0.9)
    d.text(10.0, 18.0, "EXPANSION 2x12", 1.0)
    d.text(10.0, 58.0, "PZEM-004T", 1.0)
    d.text(60.0, 66.0, "RELAYS", 1.0)
    d.text(78.0, 42.0, "PWR", 1.0)
    d.text(2.0, 68.0, "FirebaseOTA  3x6 carrier  Rev A  130x70", 1.2)

    # ------------------------------------------------------------------ document
    doc = {
        "head": "3~1.11.3~",
        "canvas": ("CA~2400~2400~#000000~yes~#FFFFFF~10~1200~1200~line~5~mil~9~45~"
                   "visible~0.5"),
        "shape": d.shapes,
        "systemColor": "#000000~#FFFFFF~#FFFFFF~#000000~#FFFFFF",
        "layers": [
            "1~TopLayer~#FF0000~true~true~true",
            "2~BottomLayer~#0000FF~true~false~true",
            "3~TopSilkLayer~#FFFF00~true~false~true",
            "4~BottomSilkLayer~#808000~true~false~true",
            "5~TopPasterLayer~#808080~false~false~false",
            "6~BottomPasterLayer~#800000~false~false~false",
            "7~TopSolderLayer~#800080~false~false~false",
            "8~BottomSolderLayer~#AA00FF~false~false~false",
            "9~Ratlines~#6464FF~false~false~true",
            "10~BoardOutline~#FF00FF~true~false~true",
            "11~Multi-Layer~#C0C0C0~true~false~true",
            "12~Document~#FFFFFF~true~false~true",
            "21~Inner1~#800000~false~false~false",
            "22~Inner2~#008000~false~false~false",
            "23~Inner3~#00FF00~false~false~false",
            "24~Inner4~#000080~false~false~false",
        ],
        "BBox": {"x": 0, "y": 0, "width": u(BOARD_W), "height": u(BOARD_H)},
        "preference": {"hideFootprints": "", "hideNets": ""},
        "DRCRULE": {
            "trackWidth": 0.7,
            "track2Track": 0.7,
            "pad2Pad": 0.8,
            "track2Pad": 0.8,
            "hole2Hole": 1,
            "holeSize": 1.6,
            "isRealtime": False,
        },
    }

    out = os.path.join(OUT_DIR, "FirebaseOTA_3x6_RevA_easyeda.json")
    with open(out, "w", encoding="utf-8") as fh:
        json.dump(doc, fh, indent=2, ensure_ascii=False)
    print(f"wrote {out}  ({len(d.shapes)} top-level shapes)")


if __name__ == "__main__":
    main()
