#!/usr/bin/env python3
"""Export BOM / CPL / netlist documents from the generated EasyEDA JSON.

The JSON is the single source of truth for pad nets, designators and positions.
Run after generate_easyeda.py:

    python3 generate_easyeda.py
    python3 export_docs.py
"""

from __future__ import annotations

import csv
import json
import os
import re
import sys
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")
REV = "RevA"
if len(sys.argv) > 1:
    _p = sys.argv[1]
    SRC = _p if os.path.isabs(_p) else os.path.join(HERE, _p)
    REV = "RevB" if "RevB" in os.path.basename(SRC) else "RevA"

BOARD_W = 130.0
BOARD_H = 70.0

# Friendly BOM description per designator.  Anything not listed falls back to
# the value stored in the LIB header.
BOM_NAMES = {
    "U1": ("ESP32 DevKit V1 30-pin module", "ESP32-DEVKIT-V1-30P",
           "pre-made module; 2 x 15-way 2.54 mm female headers"),
    "U2": ("HLK-PM01 AC/DC 5 V 3 W", "HLK-PM01", "mains input module"),
    "J1": ("2 x 14 way 2.54 mm pin header", "HDR-2X14",
           "GPIO expansion (ch 14-17 rows 13-14)"),
    "J2": ("1 x 4 way 2.54 mm pin header", "HDR-1X4", "PZEM-004T"),
    "J3": ("1 x 4 way 2.54 mm pin header", "HDR-1X4", "I2C OLED GPIO21/22"),
    "J9": ("4 way 5.08 mm terminal block", "TERM-4X5.08", "switched loads L1-L4"),
    "R2": ("2.2 kOhm 0.25 W resistor", "R-0.25W", "SSR_K1 LED input"),
    "R3": ("1 kOhm 0.25 W resistor", "R-0.25W", "SSR_K1 LED return"),
    "R4": ("2.2 kOhm 0.25 W resistor", "R-0.25W", "SSR_K2 LED input"),
    "R5": ("1 kOhm 0.25 W resistor", "R-0.25W", "SSR_K2 LED return"),
    "R6": ("2.2 kOhm 0.25 W resistor", "R-0.25W", "SSR_K3 LED input"),
    "R7": ("1 kOhm 0.25 W resistor", "R-0.25W", "SSR_K3 LED return"),
    "R8": ("2.2 kOhm 0.25 W resistor", "R-0.25W", "SSR_K4 LED input"),
    "R9": ("1 kOhm 0.25 W resistor", "R-0.25W", "SSR_K4 LED return"),
    "SSR_K1": ("Fotek SSR-25DA panel-mount SSR", "SSR-25DA-PANEL",
               "ch.1 GPIO25 / motion; remote-mount in can, SSR_Kx pads unpopulated (~$3)"),
    "SSR_K2": ("Fotek SSR-25DA panel-mount SSR", "SSR-25DA-PANEL",
               "ch.2 GPIO26 / socket 1; remote-mount in can, SSR_Kx pads unpopulated (~$3)"),
    "SSR_K3": ("Fotek SSR-25DA panel-mount SSR", "SSR-25DA-PANEL",
               "ch.3 GPIO27 / socket 2; remote-mount in can, SSR_Kx pads unpopulated (~$3)"),
    "SSR_K4": ("Fotek SSR-25DA panel-mount SSR", "SSR-25DA-PANEL",
               "ch.4 GPIO32 / temperature; remote-mount in can, SSR_Kx pads unpopulated (~$3)"),
    "J8": ("4 way 5.08 mm terminal block", "TERM-4X5.08", "AC in / AC out"),
    "F1": ("2 way 5.08 mm terminal block", "TERM-2X5.08",
           "accepts a 5 x 20 mm inline fuse"),
    "MOV1": ("MOV 14 mm 275 VAC", "MOV-14MM", "surge clamp"),
    "D1": ("SS34 Schottky diode", "DO-214AC", "reverse protection"),
    "C1": ("470 uF 16 V electrolytic", "CAP-ELEC-6.3", "5 V bulk"),
    "R1": ("1 kOhm 0.25 W resistor", "R-0.25W", "LED series"),
    "LED1": ("3 mm LED", "LED-3MM", "5 V power indicator"),
}

# Rev B overrides / additions (ESP32-WROOM-32E board): keyed by designator,
# merged over BOM_NAMES when exporting from RevB_wroom.json.
BOM_NAMES_REVB = {
    "U1": ("ESP32-WROOM-32E-N4 module (soldered)", "ESP32-WROOM-32E",
           "castellated module; antenna keep-clear at the top edge"),
    "U3": ("AMS1117-3.3 LDO", "SOT-223-3_TabPin2",
           "5 V -> 3.3 V for U1/J1/J3 (LCSC C6186)"),
    "SW1": ("6 x 6 mm tactile switch", "SW-6MM-THT", "RESET (EN)"),
    "SW2": ("6 x 6 mm tactile switch", "SW-6MM-THT", "BOOT (GPIO0)"),
    "J5": ("1 x 6 way 2.54 mm pin header", "HDR-1X6",
           "UART programming: TX RX EN IO0 + 3V3/GND"),
    "R10": ("10 kOhm 0.25 W resistor", "R-025W", "EN pull-up (datasheet RC)"),
    "R11": ("10 kOhm 0.25 W resistor", "R-025W", "GPIO0 BOOT pull-up"),
    "C2": ("1 uF electrolytic", "CAP-ELEC-6.3", "EN power-on delay (10k + 1uF)"),
    "C3": ("10 uF electrolytic", "CAP-ELEC-6.3", "LDO input rail"),
    "C4": ("10 uF electrolytic", "CAP-ELEC-6.3", "LDO output (stability)"),
    "C5": ("100 nF ceramic", "C-DISC", "3V3 decoupling at U1"),
}


def bom_names_for(ref: str) -> tuple[str, str, str]:
    if REV == "RevB" and ref in BOM_NAMES_REVB:
        return BOM_NAMES_REVB[ref]
    return BOM_NAMES.get(ref, ("", "", ""))

DEVKIT_PHYS = {
    # net: (GPIO, physical pin, side)
    "3V3": ("3V3", 1, "left"),
    "GND": ("GND", 2, "left"),
    "GPIO15": ("GPIO15", 3, "left"),
    "GPIO2": ("GPIO2", 4, "left"),
    "GPIO4": ("GPIO4", 5, "left"),
    "GPIO16": ("GPIO16", 6, "left"),
    "GPIO17": ("GPIO17", 7, "left"),
    "GPIO5": ("GPIO5", 8, "left"),
    "GPIO18": ("GPIO18", 9, "left"),
    "GPIO19": ("GPIO19", 10, "left"),
    "GPIO21": ("GPIO21", 11, "left"),
    "GPIO3": ("GPIO3", 12, "left"),
    "GPIO1": ("GPIO1", 13, "left"),
    "GPIO22": ("GPIO22", 14, "left"),
    "GPIO23": ("GPIO23", 15, "left"),
    "5V": ("VIN", 16, "right"),
    "GPIO13": ("GPIO13", 17, "right"),
    "GPIO12": ("GPIO12", 18, "right"),
    "GPIO14": ("GPIO14", 19, "right"),
    "GPIO27": ("GPIO27", 20, "right"),
    "GPIO26": ("GPIO26", 21, "right"),
    "GPIO25": ("GPIO25", 22, "right"),
    "GPIO33": ("GPIO33", 23, "right"),
    "GPIO32": ("GPIO32", 24, "right"),
    "GPIO35": ("GPIO35", 25, "right"),
    "GPIO34": ("GPIO34", 26, "right"),
    "GPIO39": ("GPIO39", 27, "right"),
    "GPIO36": ("GPIO36", 28, "right"),
    "EN": ("EN", 29, "right"),
    # physical pin 30 is the second GND on the right row
}

# Extra BOM lines that have no PCB footprint of their own.
ACCESSORIES = [
    ("Fuse 5 x 20 mm, 500 mA slow-blow", "F1 fuse", "1",
     "fits the F1 terminal block"),
    ("M3 x 8 mm screw", "H1-H4", "8",
     "4 fitted, 4 spare; PCB standoffs / tray retention"),
    ("3.5 x 12 mm countersunk screw + nut (M3 x 12 also fits)", "W1-W4", "4",
     "faceplate to the can ears; a nut sits on the back of each ear"),
    ("M20 cable gland", "G1", "1",
     "mains in / switched load out through the back can"),
    ("M12 cable gland", "G2", "1",
     "sensor / PZEM cable through the back can"),
    ("2 x 15 way 2.54 mm female header", "U1 sockets", "2",
     "solder to carrier; DevKit plugs in"),
    ("2 x 15 way 2.54 mm male header", "U1 pins", "2",
     "usually supplied with the DevKit"),
]


def parse() -> tuple[list[dict], list[dict]]:
    doc = json.load(open(SRC, encoding="utf-8"))
    parts: list[dict] = []
    nets: dict[str, list[tuple[str, str]]] = defaultdict(list)

    for s in doc["shape"]:
        if not s.startswith("LIB~"):
            continue
        head, *children = s.split("#@$")
        h = head.split("~")
        x, y = float(h[1]) / U, float(h[2]) / U
        params = h[3].split("`")
        package = params[1] if len(params) > 1 else ""
        value = params[3] if len(params) > 3 else ""
        rotation = int(float(h[4])) if len(h) > 4 and h[4] else 0
        ref = "?"
        pads = []
        for c in children:
            f = c.split("~")
            if f[0] == "TEXT" and len(f) > 1 and f[1] == "P":
                ref = f[10] if len(f) > 10 else "?"
            elif f[0] == "PAD":
                net, number = f[7], f[8]
                pads.append((net, number, float(f[2]) / U, float(f[3]) / U))
                nets[net].append((ref, number))
        parts.append({
            "ref": ref, "value": value, "package": package,
            "x": x, "y": y, "rotation": rotation, "pads": pads,
        })
    return parts, nets


def write_bom(parts: list[dict]) -> None:
    groups: dict[tuple[str, str], list[str]] = defaultdict(list)
    for p in parts:
        name, pkg, _ = bom_names_for(p["ref"]) or (p["value"], p["package"], "")
        if not name:
            name, pkg = p["value"], p["package"]
        groups[(name, pkg)].append(p["ref"])

    path = os.path.join(HERE, f"BOM_{REV}.csv")
    with open(path, "w", newline="", encoding="utf-8") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["Comment", "Designator", "Footprint", "Quantity", "Notes"])
        for (name, pkg), refs in sorted(groups.items(), key=lambda kv: kv[1][0]):
            refs = sorted(refs, key=lambda r: (re.sub(r"\d", "", r), int(re.sub(r"\D", "", r) or 0)))
            note = bom_names_for(refs[0])[2]
            w.writerow([name, ", ".join(refs), pkg, len(refs), note])
        for name, ref, qty, note in ACCESSORIES:
            w.writerow([name, ref, "", qty, note])
    print("wrote", path)


def write_cpl(parts: list[dict]) -> None:
    path = os.path.join(HERE, f"CPL_{REV}.csv")
    with open(path, "w", newline="", encoding="utf-8") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["Designator", "Mid X (mm)", "Mid Y (mm)", "Layer", "Rotation"])
        for p in sorted(parts, key=lambda p: (re.sub(r"\d", "", p["ref"]),
                                              int(re.sub(r"\D", "", p["ref"]) or 0))):
            # EasyEDA origin is top-left; assembly houses expect bottom-left.
            w.writerow([p["ref"], f"{p['x']:.2f}", f"{BOARD_H - p['y']:.2f}",
                        "Top", p["rotation"]])
    print("wrote", path)


def write_netlist(parts: list[dict], nets: dict[str, list[tuple[str, str]]]) -> None:
    path = os.path.join(HERE, f"NETLIST_{REV}.md")
    by_ref = {p["ref"]: p for p in parts}
    lines = [
        f"# FirebaseOTA 3x6 carrier - {REV.replace('Rev', 'Rev ')} netlist",
        "",
        f"Board: **{BOARD_W:.0f} x {BOARD_H:.0f} mm**, 2 layers, 1.6 mm FR-4.",
        f"Generated from `{os.path.basename(SRC)}`.",
        "",
        "## Net summary",
        "",
        "| Net | Pads | Connections |",
        "|---|---:|---|",
    ]
    for net in sorted(nets):
        conns = sorted(set(f"{r}.{n}" for r, n in nets[net]))
        lines.append(f"| `{net}` | {len(nets[net])} | {', '.join(conns)} |")

    lines += [
        "",
        "## Connector pinouts",
        "",
        "### J8 - AC in / out (5.08 mm)",
        "",
        "| Pin | Net | Use |",
        "|---:|---|---|",
        "| 1 | AC_L | mains live in |",
        "| 2 | AC_L_F | fused live out (relay / load) |",
        "| 3 | AC_N | mains neutral out |",
        "| 4 | AC_N | mains neutral in |",
        "",
        "Wire mains **in** to pins 1 and 4.  Take the switched feed for the",
        "relay module or load from pins 2 and 3.  The fuse is in series between",
        "pins 1 and 2.  The MOV clamps L-N on the incoming side; the fuse",
        "is in series with the live feed to the HLK and the load.",
        "",
        "### J1 - GPIO expansion (2 x 12, 2.54 mm)",
        "",
        "| Pin | Net | Pin | Net |",
        "|---:|---|---:|---|",
    ]
    j1_pins = [p for p in parts if p["ref"] == "J1"][0]["pads"]
    j1_map = {num: net for net, num, _x, _y in j1_pins}
    for r in range(12):
        a = j1_map.get(str(2 * r + 1), "")
        b = j1_map.get(str(2 * r + 2), "")
        lines.append(f"| {2*r+1} | `{a}` | {2*r+2} | `{b}` |")

    lines += [
        "",
        "### J2 - PZEM-004T (1 x 4, 2.54 mm)",
        "",
        "| Pin | Net |",
        "|---:|---|",
    ]
    for net, num, _x, _y in [p for p in parts if p["ref"] == "J2"][0]["pads"]:
        lines.append(f"| {num} | `{net}` |")
    lines += ["", "### J3 - OLED I2C (1 x 4, 2.54 mm)", "", "| Pin | Net |", "|---:|---|"]
    for net, num, _x, _y in [p for p in parts if p["ref"] == "J3"][0]["pads"]:
        lines.append(f"| {num} | `{net}` |")
    lines += ["", "### J9 - switched loads (1 x 4, 5.08 mm)", "", "| Pin | Net |",
              "|---:|---|"]

    lines += [
        "",
        "### SSR channels K1-K4 (Fotek SSR-25DA panel modules, remote-mounted in can)",
        "",
        "> **Production swap (2026-11-06):** the relays are now **Fotek SSR-25DA panel modules",
        "> (~$3 each)**, mounted inside the enclosure can, *not* on the carrier PCB.",
        "> The `SSR_Kx` pads on the board stay **unpopulated** (they remain valid as a",
        "> test/wire-anchor point); the modules are wired straight from the header pins:",
        "",
        "| Ref | Pin | Net | Function |", "|---|---:|---|---|",
    ]
    nice = {"1": "1 (anode, 2.2k from GPIO)", "2": "2 (cathode, 1k to GND)",
            "3": "3 (COM -> AC_N)", "4": "4 (NO -> switched load)"}
    for i in (1, 2, 3, 4):
        pads = {num: net for net, num, _x, _y in
                [p for p in parts if p["ref"] == f"SSR_K{i}"][0]["pads"]}
        for num in ("1", "2", "3", "4"):
            lines.append(f"| SSR_K{i} | {num} | `{pads.get(num, '')}` | "
                         f"{nice.get(num, '')} |")

    lines += ["", '#### Wiring the SSR-25DA panel modules (actual production connection)\n\nEach Fotek-style SSR-25DA has 4 screw terminals: `+DC` / `−DC` (control input,\n3–32 V DC) on the DC side and `LOAD` in / `LOAD` out (two mains terminals) on\nthe output side.  Mains feed for the modules is the fused live **J8.2\n(`AC_L_F`)**; the switched outputs go to **J9.1–J9.4 (`L1`–`L4`)**; control\ncomes from **J1 rows 13/14** (GPIO25/26/27/32 + shared GND):\n\n| Module | +DC (input +) | −DC (input −) | LOAD in | LOAD out |\n|---|---|---|---|---|\n| SSR-25DA #1 | J1 GPIO25 | J1 GND | J8.2 `AC_L_F` | J9.1 `L1` |\n| SSR-25DA #2 | J1 GPIO26 | J1 GND | J8.2 `AC_L_F` | J9.2 `L2` |\n| SSR-25DA #3 | J1 GPIO27 | J1 GND | J8.2 `AC_L_F` | J9.3 `L3` |\n| SSR-25DA #4 | J1 GPIO32 | J1 GND | J8.2 `AC_L_F` | J9.4 `L4` |\n\nNotes:\n- 3.3 V GPIO sits at the bottom of the 3–32 V input spec — tested working on\n  most modules; if a unit does not trigger, link its `+DC` to the 5 V pin on\n  J1 row 13 and let the 2.2 k series resistor (R2/R4/R6/R8, unpopulated\n  default) drop the difference.\n- At 2 A/channel the modules dissipate <1 W — thermal paste onto the can floor\n  is enough, no heatsink required.',]
    lines += ["", 
        "## ESP32 DevKit physical pin map",
        "",
        "The carrier uses the DOIT ESP32 DevKit V1 **30-pin** pinout with the",
        "antenna at the top and USB at the bottom.  Both lists run top to bottom.",
        "Carrier pad numbers follow the EasyEDA footprint: U1.1-U1.15 on the",
        "left, U1.30-U1.16 on the right (so U1.30 is the top-right pad).",
        "",
        "| Row position | Side | Carrier pad | Module label | Net |",
        "|---:|---|---:|---|---|",
    ]
    dev_pads = [p for p in parts if p["ref"] == "U1"][0]["pads"]
    left = sorted((p for p in dev_pads if p[2] < 40), key=lambda p: p[3])
    right = sorted((p for p in dev_pads if p[2] > 40), key=lambda p: p[3])
    for idx, (net, num, _x, _y) in enumerate(left, start=1):
        lines.append(f"| {idx} | left | U1.{num} | {net} | `{net}` |")
    for idx, (net, num, _x, _y) in enumerate(right, start=1):
        lines.append(f"| {idx} | right | U1.{num} | {net} | `{net}` |")

    lines += [
        "",
        "## Pre-routed copper",
        "",
        "- Mains: `AC_L`, `AC_L_F`, `AC_N` on the top layer, 1.5 mm wide,",
        "  kept >= 5 mm apart and >= 3 mm from any SELV track/pad.",
        "- HLK 5 V output: `5V_RAW` -> D1 -> `5V` and `GND`, 1.0 mm.",
        "- All logic/GPIO connections are left to the EasyEDA autorouter.",
        "",
        "## Safety",
        "",
        "- This board switches and carries **230 V AC**.  Build it only if you",
        "  are competent to work with mains; otherwise buy a certified module.",
        "- Keep the mains area clear of touching fingers and low-voltage wiring.",
        "- Use a fused, RCD-protected supply and a 500 mA fuse.",
        "- The HLK-PM01 provides isolation, but the AC side must still be",
        "  treated as live at all times.",
        "",
    ]
    open(path, "w", encoding="utf-8").write("\n".join(lines))
    print("wrote", path)


def main() -> None:
    parts, nets = parse()
    print(f"{len(parts)} footprints, {len(nets)} nets")
    write_bom(parts)
    write_cpl(parts)
    write_netlist(parts, nets)


if __name__ == "__main__":
    main()
