#!/usr/bin/env python3
"""
Generate an EasyEDA Standard (Std) PCB JSON for the FirebaseOTA 3x6 Rev A (v2)
carrier board — firmware-verified corrected version.

  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 (GPIO16/17), SSD1306 OLED (GPIO18/19 I2C),
            4x solid-state relays (GPIO25/26/27/32) + resistor drivers,
            2 x 12 GPIO expansion, AC in/out terminals

v2.1: OLED I2C back on GPIO21/22 (J3); J1 no longer carries those pins.

FIXES vs the earlier draft (verified against src/main.cpp +
IoTOfflineControllerEngine.h / WebDashboard.h):
  * J3 OLED I2C moved GPIO21/22 -> GPIO18/19 (21/22 are firmware
    "light 1"/"light 3" switchable outputs; 18/19 = unused "ac"/"tv").
  * GPIO12 (flash strap), GPIO16/17 (PZEM UART) and GPIO25/26/27/32
    (SSR drive) are NOT broken out on J1; the four J4-J7 expansion
    headers that duplicated the SSR GPIOs are gone.
  * Relays K1/K3 + K2/K4 were stacked on identical footprints, J9 was
    duplicated and ghost driver pads floated on the sheet — replaced by
    a clean 4x SSR (Crydom ODN2225) row + R2-R9 driver resistors.
  * Complete, crossing-free mains copper (AC_L / AC_L_F / AC_N) with
    >= 8 mm creepage to every SELV pad away from SSR input copper
    (check_board_v2.py).

GPIO / expansion / OLED / PZEM signal copper is deliberately left to the
EasyEDA ratlines + autorouter (the net list is complete); only the mains,
the 5 V rail and the per-channel SSR driver stubs are pre-routed here.

Import with EasyEDA Std:  File -> Open -> EasyEDA Source, paste, Apply.
All coordinates are millimetres, origin at the board's top-left.
"""

from __future__ import annotations

from stroke_font import text_path_str  # EasyEDA renders TEXT from pathStr
import json
import math
import os

U = 1.0 / 0.254
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}"

    def track(self, width_mm, layer, net, pts) -> None:
        self.shapes.append(
            f"TRACK~{u(width_mm)}~{layer}~{net}~"
            + " ".join(pt(x, y) for x, y in pts)
            + f"~{self.gid()}"
        )

    def hole(self, x, y, d_mm) -> None:
        # HOLE field = RADIUS (EasyEDA reads it that way)
        self.shapes.append(f"HOLE~{u(x)}~{u(y)}~{u(d_mm / 2)}~{self.gid()}")

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

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

    def solid_region(self, pts, kind="cutout", layer=10, net="") -> None:
        self.shapes.append(
            f"SOLIDREGION~{layer}~{net}~" + " ".join(pt(a, b) for a, b in pts) +
            f"~{kind}~{self.gid()}"
        )

    def footprint(self, ref, value, package, x, y, pads, silk, rotation=0) -> None:
        header = (f"LIB~{u(x)}~{u(y)}~package`{package}`value`{value}"
                  f"~{rotation}~~{self.gid()}~1")
        designator = (f"TEXT~L~{u(x)}~{u(y - 4.5)}~{u(0.15)}~0~none~3~~5~"
                      f"{ref}~{text_path_str(ref, u(x), u(y - 4.5),5)}~~"
                      f"{self.gid()}")
        children = [designator] + list(silk) + list(pads)
        self.shapes.append(header + ("#@$" + "#@$".join(children) if children else ""))


def rounded_rect(w, h, r, segments=8):
    pts = []
    corners = [(w - r, r, -90.0, 0.0), (w - r, h - r, 0.0, 90.0),
               (r, h - r, 90.0, 180.0), (r, r, 180.0, 270.0)]
    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 silk_rect(doc, x, y, w, h, width=0.25):
    pts = [(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)]
    return [f"TRACK~{u(width)}~3~~" + " ".join(pt(a, b) for a, b in pts) +
            f"~{doc.gid()}"]


def silk_circle(doc, x, y, r, width=0.25):
    return [f"CIRCLE~{u(x)}~{u(y)}~{u(r)}~{u(width)}~3~{doc.gid()}"]


def main(rev: str = "A") -> None:
    d = Doc()

    # ---------------------------------------------------------------- outline
    d.track(0.25, 10, "", rounded_rect(BOARD_W, BOARD_H, CORNER_R))
    # creepage slot under the HLK-PM01 (mains | SELV boundary)
    d.solid_region([(96.0, 9.0), (97.0, 9.0), (97.0, 27.0), (96.0, 27.0)], "cutout")

    # ---------------------------------------------------------------- mounting
    for x, y in [(14.0, 14.0), (116.0, 14.0), (116.0, 56.0), (14.0, 56.0)]:
        d.hole(x, y, 3.2)
    for x, y in [(4.7, 4.85), (125.3, 4.85), (125.3, 65.15), (4.7, 65.15)]:
        d.hole(x, y, 4.5)
    # 20 mm mains gland + 12 mm sensor gland pass-throughs (can floor)
    d.hole(99.0, 43.0, 20.0)
    d.hole(80.0, 55.0, 12.0)
    # user-added extras (Pro edit): probe/mount points
    d.hole(17.8, 11.4, 2.55)
    d.hole(114.3, 15.2, 2.55)
    d.hole(109.2, 58.4, 3.2)

    if rev == "A":
        # ---------------------------------------------------------------- DevKit U1
        left = ["3V3", "GND", "GPIO15", "GPIO2", "GPIO4", "GPIO16", "GPIO17",
                "GPIO5", "GPIO18", "GPIO19", "GPIO21", "GPIO3", "GPIO1",
                "GPIO22", "GPIO23"]
        right = ["5V", "GND", "GPIO13", "GPIO12", "GPIO14", "GPIO27", "GPIO26",
                 "GPIO25", "GPIO33", "GPIO32", "GPIO35", "GPIO34", "GPIO39",
                 "GPIO36", "EN"]
        dev_pads = []
        for i in range(15):
            y = 12.1 + i * 2.54
            dev_pads.append(d.pad(27.97, y, 2.0, 2.0, left[i], str(i + 1),
                                  1.0, "RECT" if i == 0 else "ELLIPSE"))
            dev_pads.append(d.pad(50.83, 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)
    else:
        # ---------------------------------------------------------------- Rev B: ESP32-WROOM-32E U1
        # Soldered module replacing the DevKit (same nets, new pads).
        # Land pattern from the Espressif datasheet v2.1 / KiCad
        # RF_Module:ESP32-WROOM-32: pads on three sides (14 left + 10 bottom
        # + 14 right = 38),1.27 mm pitch, columns +-8.75, bottom row y+9.51,
        # antenna at the top end -> keep-out: no copper under the antenna.
        wx, wy = 39.4, 18.24          # antenna tip lands at board y=2.5
        # flash pins17-22 (+32) are not brought out: each gets its own
        # one-pad net so EasyEDA's DRC does not report them as
        # "disconnected from other objects of the same network".
        wroom_nets = {
            1: "GND", 2: "3V3", 3: "EN", 4: "GPIO36", 5: "GPIO39",
            6: "GPIO34", 7: "GPIO35", 8: "GPIO32", 9: "GPIO33",
            10: "GPIO25", 11: "GPIO26", 12: "GPIO27", 13: "GPIO14",
            14: "GPIO12", 15: "GND", 16: "GPIO13", 17: "NC17", 18: "NC18",
            19: "NC19", 20: "NC20", 21: "NC21", 22: "NC22", 23: "GPIO15",
            24: "GPIO2", 25: "GPIO0", 26: "GPIO4", 27: "GPIO16",
            28: "GPIO17", 29: "GPIO5", 30: "GPIO18", 31: "GPIO19",
            32: "NC32", 33: "GPIO21", 34: "GPIO3", 35: "GPIO1",
            36: "GPIO22", 37: "GPIO23", 38: "GND",
        }
        wr_pads = []
        for i in range(14):            # left column, pin1 top (antenna end)
            n = i + 1
            wr_pads.append(d.pad(wx - 8.75, wy - 8.25 + i * 1.27, 1.5, 0.9,
                                 wroom_nets[n], str(n), 0,
                                 "RECT" if n == 1 else "ELLIPSE", layer=1))
        for i in range(10):            # bottom row (opposite the antenna)
            n = 15 + i
            wr_pads.append(d.pad(wx - 5.71 + i * 1.27, wy + 9.51, 0.9, 1.5,
                                 wroom_nets[n], str(n), 0, "ELLIPSE", layer=1))
        for i in range(14):            # right column, pin38 top
            n = 38 - i
            wr_pads.append(d.pad(wx + 8.75, wy - 8.25 + i * 1.27, 1.5, 0.9,
                                 wroom_nets[n], str(n), 0, "ELLIPSE", layer=1))
        wr_pads.append(d.pad(wx - 0.68, wy - 0.91, 4.2, 4.2, "GND", "39",
                             0, "RECT", layer=1))
        wr_silk = silk_rect(d, wx - 9.0, wy - 15.74, 18.0, 25.5)
        wr_silk += [f"TRACK~{u(0.25)}~3~~"
                    f"{pt(wx - 9.0, wy - 9.8)} {pt(wx + 9.0, wy - 9.8)}~{d.gid()}"]
        d.footprint("U1", "ESP32-WROOM-32E", "ESP32-WROOM-32E",
                    wx, wy, wr_pads, wr_silk)

        # ---- Rev B support circuit: what the DevKit carried on-board.
        # U3 AMS1117-3.3 (SOT-223-3 TabPin2):5 V ->3 V3 for U1/J1/J3.
        u3x, u3y = 47.0, 34.0
        u3_pads = [
            d.pad(u3x - 3.15, u3y - 2.3, 2.0, 1.5, "GND", "1", 0, "RECT",
                  layer=1),
            d.pad(u3x - 3.15, u3y, 2.0, 1.5, "3V3", "2", 0, "RECT", layer=1),
            d.pad(u3x - 3.15, u3y + 2.3, 2.0, 1.5, "5V", "3", 0, "RECT",
                  layer=1),
            d.pad(u3x + 3.15, u3y, 2.0, 3.8, "3V3", "2", 0, "RECT", layer=1),
        ]
        d.footprint("U3", "AMS1117-3.3", "SOT-223-3_TabPin2",
                    u3x, u3y, u3_pads,
                    silk_rect(d, u3x - 1.85, u3y - 3.35, 3.7, 6.7))

        # R10 EN pull-up10k (datasheet RC: R=10k), C2 =1uF EN delay
        r10_pads = [d.pad(26.0, 22.4, 2.2, 2.2, "EN", "1", 0.8, "RECT"),
                    d.pad(26.0, 24.94, 2.2, 2.2, "3V3", "2", 0.8)]
        d.footprint("R10", "10k", "R-0.25W", 26.0, 23.67, r10_pads,
                    silk_rect(d, 24.7, 20.81, 2.6, 5.7))
        c2_pads = [d.pad(26.5, 29.6, 2.2, 2.2, "EN", "1", 0.9, "RECT"),
                   d.pad(26.5, 32.14, 2.2, 2.2, "GND", "2", 0.9)]
        d.footprint("C2", "1uF (EN delay)", "CAP-ELEC-6.3", 26.5, 29.87,
                    c2_pads, silk_circle(d, 26.5, 29.87, 3.0))

        # R11 GPIO0 (BOOT) pull-up10k; SW1 reset, SW2 boot (6mm tact:
        # each end's two legs are one terminal -> pair pads by y)
        r11_pads = [d.pad(52.0, 23.0, 2.2, 2.2, "GPIO0", "1", 0.8, "RECT"),
                    d.pad(52.0, 25.54, 2.2, 2.2, "3V3", "2", 0.8)]
        d.footprint("R11", "10k", "R-025W", 52.0, 24.27,
                    r11_pads, silk_rect(d, 50.7, 21.41, 2.6, 5.7))
        sw1_pads = [d.pad(23.75, 11.75, 1.8, 1.8, "EN", "1", 0.9, "RECT"),
                    d.pad(28.25, 11.75, 1.8, 1.8, "EN", "2", 0.9),
                    d.pad(23.75, 18.25, 1.8, 1.8, "GND", "3", 0.9),
                    d.pad(28.25, 18.25, 1.8, 1.8, "GND", "4", 0.9)]
        d.footprint("SW1", "RESET", "SW-6MM-THT", 26.0, 15.0, sw1_pads,
                    silk_rect(d, 23.0, 12.0, 6.0, 6.0))
        sw2_pads = [d.pad(25.75, 34.55, 1.8, 1.8, "GPIO0", "1", 0.9, "RECT"),
                    d.pad(30.25, 34.55, 1.8, 1.8, "GPIO0", "2", 0.9),
                    d.pad(25.75, 41.05, 1.8, 1.8, "GND", "3", 0.9),
                    d.pad(30.25, 41.05, 1.8, 1.8, "GND", "4", 0.9)]
        d.footprint("SW2", "BOOT", "SW-6MM-THT", 28.0, 37.8, sw2_pads,
                    silk_rect(d, 25.0, 34.8, 6.0, 6.0))

        # LDO rail caps:5V input,3V3 output (AMS1117 needs >=10uF out)
        c3_pads = [d.pad(44.0, 40.7, 2.2, 2.2, "5V", "1", 0.9, "RECT"),
                   d.pad(44.0, 43.24, 2.2, 2.2, "GND", "2", 0.9)]
        d.footprint("C3", "10uF", "CAP-ELEC-6.3", 44.0, 40.97, c3_pads,
                    silk_circle(d, 44.0, 40.97, 3.0))
        c4_pads = [d.pad(39.0, 31.2, 2.2, 2.2, "3V3", "1", 0.9, "RECT"),
                   d.pad(39.0, 33.74, 2.2, 2.2, "GND", "2", 0.9)]
        d.footprint("C4", "10uF", "CAP-ELEC-6.3", 39.0, 31.47, c4_pads,
                    silk_circle(d, 39.0, 31.47, 3.0))
        c5_pads = [d.pad(26.0, 9.0, 1.8, 1.8, "3V3", "1", 0.9, "RECT"),
                   d.pad(28.5, 9.0, 1.8, 1.8, "GND", "2", 0.9)]
        d.footprint("C5", "100nF", "C-DISC", 27.25, 9.27, c5_pads,
                    silk_circle(d, 27.25, 9.27, 2.5))

        # J5 programming / UART header1x6: TX/RX/EN/IO0 + power
        j5_nets = ["GPIO1", "GPIO3", "EN", "GPIO0", "3V3", "GND"]
        j5_pads = []
        for i, net in enumerate(j5_nets):
            j5_pads.append(d.pad(21.0, 9.4 + i * 2.54, 1.8, 1.8, net,
                                 str(i + 1), 1.0,
                                 "RECT" if i == 0 else "ELLIPSE"))
        d.footprint("J5", "UART (TX RX EN IO0)", "HDR-1X6", 21.0, 15.75,
                    j5_pads, silk_rect(d, 19.2, 7.56, 3.6, 16.48))

    # ---------------------------------------------------------------- HLK-PM01 U2
    hl_x, hl_y = 102.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),
    ]
    d.footprint("U2", "HLK-PM01", "HLK-PM01", hl_x, hl_y, hlk_pads,
                silk_rect(d, 85.0, 7.9, 34.0, 20.2))

    # ---------------------------------------------------------------- J8 AC in/out
    j8_pads = [
        d.pad(71.0, 8.0, 2.8, 2.8, "AC_L", "1", 1.3, "RECT"),
        d.pad(71.0, 13.08, 2.8, 2.8, "AC_L_F", "2", 1.3),
        d.pad(71.0, 18.16, 2.8, 2.8, "AC_N", "3", 1.3),
        d.pad(71.0, 23.24, 2.8, 2.8, "AC_N", "4", 1.3),
    ]
    d.footprint("J8", "AC IN / OUT 230V", "TERM-4X5.08", 71.0, 15.62, j8_pads,
                silk_rect(d, 68.2, 5.2, 5.6, 21.04))

    # ---------------------------------------------------------------- F1 fuse (inline 5x20 holder)
    # NOTE: the v2.1 "Pro edit" moved F1 east to (68.55, 16.5). That spot is
    # unbuildable - pad 1 (AC_L) landed on top of J8.3 (AC_N), a dead mains
    # short - and the holder body collided with J8.  F1 therefore stays at
    # its verified position; the rest of that edit (mount/probe holes,
    # R1/LED1 nudge, J1 2x14, SSR_K4 row) is kept.
    f1_pads = [
        d.pad(67.0, 16.0, 3.0, 3.0, "AC_L", "1", 1.3, "RECT"),
        d.pad(61.92, 16.0, 3.0, 3.0, "AC_L_F", "2", 1.3),
    ]
    d.footprint("F1", "FUSE 500mA inline", "TERM-2X5.08", 64.46, 16.0, f1_pads,
                silk_rect(d, 59.9, 13.8, 7.2, 4.4))

    # ---------------------------------------------------------------- MOV1
    mov_pads = [
        d.pad(67.0, 34.0, 3.0, 3.0, "AC_L", "1", 1.1, "RECT"),
        d.pad(74.5, 34.0, 3.0, 3.0, "AC_N", "2", 1.1),
    ]
    d.footprint("MOV1", "MOV 275VAC", "MOV-14MM", 70.75, 34.0, mov_pads,
                silk_rect(d, 64.5, 30.5, 13.0, 7.0))

    # ---------------------------------------------------------------- D1 / C1 (5V rail)
    # moved clear of J9 pads (>= 8 mm rule to L-pins)
    d1_pads = [
        d.pad(112.6, 36.0, 2.6, 2.6, "5V_RAW", "1", 1.0, "RECT"),
        d.pad(108.5, 36.0, 2.6, 2.6, "5V", "2", 1.0),
    ]
    d.footprint("D1", "SS34", "DO-214AC", 110.55, 36.0, d1_pads,
                silk_rect(d, 106.4, 33.7, 8.5, 4.6))
    c1_pads = [
        d.pad(112.0, 41.13, 2.2, 2.2, "5V", "1", 0.9, "RECT"),
        d.pad(112.0, 43.67, 2.2, 2.2, "GND", "2", 0.9),
    ]
    d.footprint("C1", "470uF 16V", "CAP-ELEC-6.3", 112.0, 41.4, c1_pads,
                silk_circle(d, 112.0, 41.4, 3.0))

    # ---------------------------------------------------------------- R1 / LED1 (5V power LED)
    r1_pads = [
        d.pad(59.66, 48.29, 2.2, 2.2, "LED_A", "1", 0.8, "RECT"),
        d.pad(59.66, 50.76, 2.2, 2.2, "5V", "2", 0.8),
    ]
    d.footprint("R1", "1k", "R-0.25W", 59.66, 49.53, r1_pads,
                silk_rect(d, 58.36, 46.7, 2.6, 5.7))
    led_pads = [
        d.pad(63.5, 48.29, 2.2, 2.2, "LED_A", "1", 0.8, "RECT"),
        d.pad(63.5, 50.76, 2.2, 2.2, "GND", "2", 0.8),
    ]
    d.footprint("LED1", "PWR LED", "LED-3MM", 63.5, 49.53, led_pads,
                silk_circle(d, 63.5, 49.53, 1.6))

    # ---------------------------------------------------------------- J1 GPIO expansion 2x12
    # GPIO21/22 are dedicated to the SSD1306 OLED I2C (J3) and stay off this
    # header; GPIO12 (flash strap) and GPIO16/17 (PZEM UART) never break out.
    # Four SSR-channel rows (13/14) expose the channel GPIOs for external
    # relay/SSR modules: GPIO25(motion), GPIO26(socket1), GPIO27(socket2),
    # GPIO32(temperature) - same nets that drive the on-board R2/R4/R6/R8.
    exp_nets = ["3V3", "5V", "GND", "GND",
                "GPIO2", "GPIO4", "GPIO5", "GPIO13",
                "GPIO14", "GND", "GND", "GPIO23",
                "GPIO33", "GPIO34", "GPIO35", "GPIO15",
                "GPIO25", "GPIO26", "GPIO27", "GPIO32",
                "GND", "GND", "GND", "GND", "GND", "GND", "GND", "GND"]
    j1x, j1y = 5.27, 22.0
    j1_pads = []
    for r in range(14):
        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))
    d.footprint("J1", "GPIO EXP 2x14 (21/22=OLED; 12/16/17 n/b; ch14-17 rows 13-14)", "HDR-2X14",
                j1x + 1.27, j1y + 13.97, j1_pads,
                silk_rect(d, 4.0, 20.73, 5.08, 35.56))

    # ---------------------------------------------------------------- J3 OLED I2C (GPIO18/19)
    oled_pads = [
        d.pad(14.2, 5.5, 1.8, 1.8, "3V3", "1", 1.0, "RECT"),
        d.pad(16.74, 5.5, 1.8, 1.8, "GND", "2", 1.0),
        d.pad(19.28, 5.5, 1.8, 1.8, "GPIO21", "3", 1.0),
        d.pad(21.82, 5.5, 1.8, 1.8, "GPIO22", "4", 1.0),
    ]
    d.footprint("J3", "OLED I2C GPIO21/22", "HDR-1X4", 18.01, 5.5, oled_pads,
                silk_rect(d, 12.9, 3.7, 11.4, 3.6))

    # ---------------------------------------------------------------- J2 PZEM-004T (far east, clear of SSR row)
    pzem_pads = [
        d.pad(104.0, 66.5, 1.8, 1.8, "5V", "1", 1.0, "RECT"),
        d.pad(106.54, 66.5, 1.8, 1.8, "GND", "2", 1.0),
        d.pad(109.08, 66.5, 1.8, 1.8, "GPIO16", "3", 1.0),
        d.pad(111.62, 66.5, 1.8, 1.8, "GPIO17", "4", 1.0),
    ]
    d.footprint("J2", "PZEM-004T", "HDR-1X4", 107.81, 66.5, pzem_pads,
                silk_rect(d, 102.7, 64.9, 11.2, 3.2))


    # ---------------------------------------------------------------- SSR row K1-K4 (Option B)
    # Pins: ANODE (SELV, R_A-driven), CATHODE (SELV, 1k to GND), COM -> AC_N,
    # NO -> Lk.  Channel pitch keeps each channel's SELV pins >= 10 mm clear
    # of the neighbour pins, and all channel SELV pads sit north of the
    # mains rows, so the >=8 mm rule is met outside the module moulding.
    ssr_info = [("SSR_K1", 13.7, "GPIO25", "K1 motion"),
                ("SSR_K2", 35.5, "GPIO26", "K2 socket 1"),
                ("SSR_K3", 56.0, "GPIO27", "K3 socket 2"),
                ("SSR_K4", 86.5, "GPIO32", "K4 temperature")]
    for idx, (ref, bx, gpio, name) in enumerate(ssr_info):
        y_sel = 63.2 if ref == "SSR_K4" else 61.5
        pads = [
            d.pad(bx, y_sel, 1.5, 1.5, ref + "_AN", "1", 1.0, "ELLIPSE"),
            d.pad(bx + 2.5, y_sel, 1.5, 1.5, ref + "_CAT", "2", 1.0, "ELLIPSE"),
            d.pad(bx + 5.0, y_sel, 2.0, 2.0, "AC_N", "3", 1.3, "ELLIPSE"),
            d.pad(bx + 7.5, y_sel, 2.0, 2.0, "L%d" % (idx + 1), "4", 1.3, "ELLIPSE"),
        ]
        silk = silk_rect(d, bx - 1.5, y_sel - 2.2, 11.0, 3.6)
        silk.append(f"TEXT~L~{u(bx - 1.0)}~{u(y_sel + 3.4)}~{u(0.15)}~0~none~3~~"
                    f"{round(1.0 / 0.254)}~{name}~"
                    f"{text_path_str(name, u(bx - 1.0), u(y_sel + 3.4), round(1.0 / 0.254))}~~"
                    f"{d.gid()}")
        d.footprint(ref, "SSR-ODN2225", "SOLID-STATE-RELAY", bx + 3.75, y_sel,
                    pads, silk)

    # ---------------------------------------------------------------- driver resistors R2-R9
    # All eight resistors sit in a row north of the SSR module band:
    #   R_A (2.2k): GPIO pad (north) + SSR-x_AN pad (south)
    #   R_B (1k):   SSR-x_CAT pad (north, rcx) + GND pad (south)
    # The y=42.5..47 band is >= 15 mm clear of every mains pad row, so the
    # >= 8 mm mains-to-SELV rule holds by a wide margin.  Stub tracks use a
    # vertical + short jog into the module pin, never crossing other copper.
    # per-channel driver resistor positions (R_A 2.2k at rx; R_B 1k at rcx)
    ra_pos = [(10.9, 42.5), (32.7, 42.5), (53.2, 42.5), (70.4, 44.5)]
    rcx_pos = [(17.3, 42.5), (35.3, 42.5), (55.8, 42.5), (88.3, 46.5)]
    for idx, ((ref, bx, gpio, name), (rx, ry), (rcx, rby)) in enumerate(
            zip(ssr_info, ra_pos, rcx_pos)):
        y_sel = 63.2 if ref == "SSR_K4" else 61.5
        pads = [
            d.pad(rx, ry, 1.6, 1.6, gpio, "1", 0.8, "RECT"),
            d.pad(rx, ry + 2.54, 1.6, 1.6, ref + "_AN", "2", 0.8),
        ]
        d.footprint("R%d" % (2 + idx * 2), "2.2k", "R-0.25W", rx, ry + 1.27,
                    pads, silk_rect(d, rx - 1.3, ry - 1.3, 2.6, 5.2))
        if ref == "SSR_K4":
            d.track(0.6, 1, ref + "_AN", [(rx, ry + 2.54), (rx, 63.0),
                                          (bx, 63.0), (bx, y_sel)])
        else:
            d.track(0.6, 1, ref + "_AN", [(rx, ry + 2.54), (rx, y_sel - 0.5),
                                          (bx, y_sel - 0.5), (bx, y_sel)])
        rby_cat = rby + 2.54
        pads = [
            d.pad(rcx, rby_cat, 1.6, 1.6, ref + "_CAT", "1", 0.8, "RECT"),
            d.pad(rcx, rby, 1.6, 1.6, "GND", "2", 0.8, "RECT"),
        ]
        d.footprint("R%d" % (3 + idx * 2), "1k", "R-0.25W", rcx,
                    (rby + rby_cat) / 2, pads,
                    silk_rect(d, rcx - 1.3, rby - 1.3, 2.6, 5.2))
        if ref == "SSR_K4":
            d.track(0.6, 1, ref + "_CAT", [(rcx, rby_cat), (rcx, 56.1),
                                           (bx + 2.5, 56.1), (bx + 2.5, y_sel)])
        else:
            d.track(0.6, 1, ref + "_CAT", [(rcx, rby_cat), (rcx, y_sel - 2.9),
                                           (bx + 2.5, y_sel - 2.9),
                                           (bx + 2.5, y_sel)])

    # ---------------------------------------------------------------- J9 (switched loads L1-L4)
    j9x = 124.0
    j9_pads = [
        d.pad(j9x, 40.6, 2.8, 2.8, "L1", "1", 1.3, "RECT"),
        d.pad(j9x, 45.68, 2.8, 2.8, "L2", "2", 1.3),
        d.pad(j9x, 50.76, 2.8, 2.8, "L3", "3", 1.3),
        d.pad(j9x, 55.84, 2.8, 2.8, "L4", "4", 1.3),
    ]
    d.footprint("J9", "SWITCHED LOAD L1-L4", "TERM-4X5.08", j9x, 48.22, j9_pads,
                silk_rect(d, 120.0, 37.6, 8.0, 21.0))

    # ---------------------------------------------------------------- mains copper
    d.track(1.5, 1, "AC_L", [(71.0, 8.0), (67.0, 8.0), (67.0, 34.0)])
    d.track(1.5, 1, "AC_L_F", [(71.0, 13.08), (61.92, 13.08), (61.92, 16.0)])
    d.track(1.5, 1, "AC_L_F", [(71.0, 13.08), (85.0, 13.08), (85.0, 15.5),
                               (87.3, 15.5)])
    d.track(1.5, 1, "AC_N", [(74.5, 34.0), (74.5, 18.16), (71.0, 18.16)])
    # J8.4 (AC out neutral) was left floating in the export - jumper to J8.3
    d.track(1.5, 1, "AC_N", [(71.0, 23.2), (71.0, 18.16)])
    d.track(1.5, 1, "AC_N", [(71.0, 18.16), (85.0, 18.16), (85.0, 20.5),
                             (87.3, 20.5)])

    # ---------------------------------------------------------------- 5V / GND copper
    d.track(1.0, 1, "5V_RAW", [(116.7, 25.7), (112.6, 25.7), (112.6, 36.0)])
    d.track(0.6, 1, "5V", [(108.5, 36.0), (112.0, 41.13)])
    d.track(1.0, 1, "GND", [(116.7, 10.3), (119.5, 10.3), (119.5, 43.67),
                            (112.0, 43.67)])

    # ---------------------------------------------------------------- silk notes
    d.text(67.0, 3.2, "AC IN / OUT", 1.1)
    d.text(73.0, 8.6, "FUSE 500mA", 0.9)
    d.text(64.5, 41.6, "MOV 275V", 0.9)
    d.text(54.0, 46.0, "230V AC - KEEP CLEAR", 1.2)
    d.text(110.0, 36.5, "SELV 5V", 1.2)
    d.text(12.9, 2.6, "OLED (GPIO21 SDA/22 SCL)", 0.9)
    d.text(4.0, 18.0, "EXPANSION 2x14", 1.0)
    d.text(102.7, 62.6, "PZEM-004T", 1.0)
    d.text(12.5, 55.6, "SSR K1-K4: GPIO25/26/27/32", 1.0)
    d.text(110.5, 62.0, "LOADS L1-L4", 1.0)
    if rev == "B":
        d.text(49.5, 3.0, "ANTENNA - KEEP CLEAR", 0.9)
        d.text(23.2, 19.4, "RESET", 0.8)
        d.text(25.5, 42.4, "BOOT", 0.8)
        d.text(15.0, 25.0, "J5 UART PROG", 0.9)
        d.text(2.0, 68.0, "FirebaseOTA  3x6 carrier  Rev B wroom  130x70", 1.2)
    else:
        d.text(2.0, 68.0, "FirebaseOTA  3x6 carrier  Rev A v2  130x70", 1.2)

    # ---------------------------------------------------------------- document
    doc = {
        "head": "3~1.11.3~",
        # Required by the Std editor's "Document -> Open -> EasyEDA Source":
        # without documentType/docType the pasted text is rejected as
        # "format incorrect".
        "documentType": "pcb",
        "docType": "3",
        "origin": {"x": 0, "y": 0},
        "hasID": False,
        "datastr": "",
        "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,
        },
    }

    name = ("FirebaseOTA_3x6_RevA_easyeda.json" if rev == "A"
            else "FirebaseOTA_3x6_RevB_wroom.json")
    out = os.path.join(OUT_DIR, name)
    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__":
    import sys
    main("B" if "--revb" in sys.argv[1:] else "A")
