main
Drew Owens Add KiCad 10 Spine PCB, STEP, Gerbers/BOM/CPL, and parametric mechanical CAD/STL/STEP e614ae8
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491
#!/usr/bin/env python3
"""Generate Microgoose Spine KiCad 10 symbol libraries and schematic from design/netlist.json."""

from __future__ import annotations

import json
import math
import re
import uuid
from collections import defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
KICAD_DIR = ROOT / "kicad"
LIB_DIR = KICAD_DIR / "lib"
PCM_STAGE_SYM = ROOT / "aiflow" / "run" / "project-page" / "pcm-stage" / "symbols" / "microgoose.kicad_sym"
TP_STAGE_SYM = ROOT / "design" / "testpoint" / "Adom_TestPoint_D0.5mm.kicad_sym"
NETLIST_PATH = ROOT / "design" / "netlist.json"
CALCS_PATH = ROOT / "design" / "calcs.json"

GRID = 1.27
SCH_UUID_NS = uuid.UUID("7b3c9e52-64f1-4a8e-9b14-2c8d5e103f77")


def det_uuid(tag: str) -> str:
    return str(uuid.uuid5(SCH_UUID_NS, tag))


def g(steps: int) -> float:
    return round(steps * GRID, 4)


def snap(val: float) -> float:
    return round(round(val / GRID) * GRID, 4)


def fmt(val: float) -> str:
    v = round(val, 4)
    if abs(v) < 1e-9:
        v = 0.0
    s = f"{v:.4f}".rstrip("0").rstrip(".")
    return s if s else "0"


def extract_top_symbols(sym_text: str) -> dict[str, str]:
    """Extract top-level (symbol "NAME" ...) blocks from a .kicad_sym file."""
    symbols: dict[str, str] = {}
    i = 0
    n = len(sym_text)
    # Skip outer (kicad_symbol_lib header
    first = sym_text.find("(kicad_symbol_lib")
    assert first != -1, "Not a kicad_symbol_lib"
    i = first + len("(kicad_symbol_lib")
    depth = 1
    while i < n and depth > 0:
        ch = sym_text[i]
        if ch == '"':
            i += 1
            while i < n:
                if sym_text[i] == "\\":
                    i += 2
                elif sym_text[i] == '"':
                    i += 1
                    break
                else:
                    i += 1
            continue
        if ch == "(":
            if depth == 1 and sym_text[i : i + 8] == "(symbol ":
                start = i
                sub_depth = 0
                j = i
                while j < n:
                    c2 = sym_text[j]
                    if c2 == '"':
                        j += 1
                        while j < n:
                            if sym_text[j] == "\\":
                                j += 2
                            elif sym_text[j] == '"':
                                j += 1
                                break
                            else:
                                j += 1
                        continue
                    if c2 == "(":
                        sub_depth += 1
                    elif c2 == ")":
                        sub_depth -= 1
                        if sub_depth == 0:
                            j += 1
                            break
                    j += 1
                block = sym_text[start:j]
                m = re.match(r'\(symbol\s+"([^"]+)"', block)
                assert m, f"Malformed symbol header: {block[:60]}"
                symbols[m.group(1)] = block
                i = j
                continue
            depth += 1
        elif ch == ")":
            depth -= 1
        i += 1
    return symbols


def snap_symbol_pins(block: str) -> str:
    """Snap all (pin ... (at x y rot) ...) x, y coordinates to 1.27 mm grid."""
    pin_at_re = re.compile(r"(\(pin\s+\S+\s+\S+\s*\(at\s+)([-\d.]+)\s+([-\d.]+)(\s+[-\d.]+\))")

    def repl(m: re.Match[str]) -> str:
        x = snap(float(m.group(2)))
        y = snap(float(m.group(3)))
        return f"{m.group(1)}{fmt(x)} {fmt(y)}{m.group(4)}"

    out = pin_at_re.sub(repl, block)
    # Also snap rectangle bounds on STM32G431CBT6 / WS2812B-2020 so body stays tidy around snapped pins
    out = out.replace("(end 25.40 -77.12)", "(end 25.4 -77.47)")
    out = out.replace("(end 15.24 -15.43)", "(end 15.24 -15.24)")
    # BMI270 in primary I2C mode (~CSB=3V3, ~OCSB=3V3) uses SDO, ASDX, OSDO as static strap inputs (tied to GND)
    if out.startswith('(symbol "BMI270"'):
        for strap_pin in ("SDO", "ASDX", "OSDO"):
            out = re.sub(
                r'\(pin bidirectional line(\s+\(at [^\)]+\)\s+\(length [^\)]+\)\s+\(name "' + strap_pin + r'")',
                r'(pin input line\1',
                out,
            )
    return out


def parse_symbol_info(block: str) -> dict:
    """Parse pin locations/types and body bounding box from a snapped symbol block."""
    pins: dict[str, tuple[float, float, int, str, str]] = {}
    # Find each (pin <etype> <shape> ... ) block
    idx = 0
    while True:
        p = block.find("(pin ", idx)
        if p == -1:
            break
        # Make sure it's not (pin_names or (pin_numbers
        after = block[p + 5 : p + 12]
        if after.startswith("names") or after.startswith("numbers"):
            idx = p + 5
            continue
        depth = 0
        j = p
        while j < len(block):
            c = block[j]
            if c == '"':
                j += 1
                while j < len(block):
                    if block[j] == "\\":
                        j += 2
                    elif block[j] == '"':
                        j += 1
                        break
                    else:
                        j += 1
                continue
            if c == "(":
                depth += 1
            elif c == ")":
                depth -= 1
                if depth == 0:
                    j += 1
                    break
            j += 1
        pblock = block[p:j]
        mh = re.match(r"\(pin\s+(\S+)\s+(\S+)", pblock)
        mat = re.search(r"\(at\s+([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)\)", pblock)
        mname = re.search(r'\(name\s+"([^"]*)"', pblock)
        mnum = re.search(r'\(number\s+"([^"]*)"', pblock)
        assert mh and mat and mnum, f"Cannot parse pin: {pblock}"
        etype = mh.group(1)
        px = float(mat.group(1))
        py = float(mat.group(2))
        prot = int(round(float(mat.group(3)))) % 360
        pname = mname.group(1) if mname else ""
        pnum = mnum.group(1)
        pins[pnum] = (px, py, prot, etype, pname)
        idx = j

    # Body bounding box from rectangles / polylines / circles / arcs
    xs: list[float] = []
    ys: list[float] = []
    for m in re.finditer(r"\((?:start|end|mid|center|xy)\s+([-\d.]+)\s+([-\d.]+)\)", block):
        xs.append(float(m.group(1)))
        ys.append(float(m.group(2)))
    for px, py, _, _, _ in pins.values():
        xs.append(px)
        ys.append(py)
    bbox = (min(xs), min(ys), max(xs), max(ys)) if xs else (-2.54, -2.54, 2.54, 2.54)
    return {"pins": pins, "bbox": bbox}


def prefix_lib_symbol(block: str, prefix: str, sym_name: str) -> str:
    """Rename outer (symbol "NAME" ...) to (symbol "PREFIX:NAME" ...) while keeping inner unit names."""
    return re.sub(
        r'^\(symbol\s+"' + re.escape(sym_name) + r'"',
        f'(symbol "{prefix}:{sym_name}"',
        block,
        count=1,
    )


def make_power_symbols() -> dict[str, str]:
    """Create MicrogoosePower local rail symbols and global PWR_FLAG symbol."""
    syms: dict[str, str] = {}
    for rail in ("VBAT", "5V_BUS", "3V3"):
        syms[rail] = f"""(symbol "{rail}"
  (power local)
  (pin_numbers (hide yes))
  (pin_names (offset 0) (hide yes))
  (exclude_from_sim no)
  (in_bom no)
  (on_board no)
  (property "Reference" "#PWR" (at 0 -3.81 0) (effects (font (size 1.27 1.27)) (hide yes)))
  (property "Value" "{rail}" (at 0 3.81 0) (effects (font (size 1.27 1.27))))
  (property "Footprint" "" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes)))
  (property "Datasheet" "" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes)))
  (symbol "{rail}_0_1"
    (polyline (pts (xy -1.27 2.54) (xy 1.27 2.54)) (stroke (width 0.254) (type default)) (fill (type none)))
    (polyline (pts (xy 0 0) (xy 0 2.54)) (stroke (width 0) (type default)) (fill (type none)))
  )
  (symbol "{rail}_1_1"
    (pin power_in line (at 0 0 90) (length 0)
      (name "{rail}" (effects (font (size 1.27 1.27))))
      (number "1" (effects (font (size 1.27 1.27))))
    )
  )
  (embedded_fonts no)
)"""
    syms["GND"] = """(symbol "GND"
  (power local)
  (pin_numbers (hide yes))
  (pin_names (offset 0) (hide yes))
  (exclude_from_sim no)
  (in_bom no)
  (on_board no)
  (property "Reference" "#PWR" (at 0 -6.35 0) (effects (font (size 1.27 1.27)) (hide yes)))
  (property "Value" "GND" (at 0 -5.08 0) (effects (font (size 1.27 1.27))))
  (property "Footprint" "" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes)))
  (property "Datasheet" "" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes)))
  (symbol "GND_0_1"
    (polyline (pts (xy 0 0) (xy 0 -1.27) (xy 1.27 -1.27) (xy 0 -2.54) (xy -1.27 -1.27) (xy 0 -1.27))
      (stroke (width 0) (type default)) (fill (type none)))
  )
  (symbol "GND_1_1"
    (pin power_in line (at 0 0 270) (length 0)
      (name "GND" (effects (font (size 1.27 1.27))))
      (number "1" (effects (font (size 1.27 1.27))))
    )
  )
  (embedded_fonts no)
)"""
    syms["PWR_FLAG"] = """(symbol "PWR_FLAG"
  (power global)
  (pin_numbers (hide yes))
  (pin_names (offset 0) (hide yes))
  (exclude_from_sim no)
  (in_bom no)
  (on_board no)
  (property "Reference" "#FLG" (at 0 1.905 0) (effects (font (size 1.27 1.27)) (hide yes)))
  (property "Value" "PWR_FLAG" (at 0 3.81 0) (effects (font (size 1.27 1.27))))
  (property "Footprint" "" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes)))
  (property "Datasheet" "" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes)))
  (symbol "PWR_FLAG_0_1"
    (polyline (pts (xy 0 0) (xy 0 1.27) (xy -1.016 1.905) (xy 0 2.54) (xy 1.016 1.905) (xy 0 1.27))
      (stroke (width 0) (type default)) (fill (type none)))
  )
  (symbol "PWR_FLAG_1_1"
    (pin power_out line (at 0 0 90) (length 0)
      (name "pwr" (effects (font (size 1.27 1.27))))
      (number "1" (effects (font (size 1.27 1.27))))
    )
  )
  (embedded_fonts no)
)"""
    return syms


def pin_sheet_xy(sx: float, sy: float, cx: float, cy: float, rot_deg: int) -> tuple[float, float]:
    """Exact KiCad symbol-to-sheet coordinate transform (Y-up symbol -> Y-down sheet, rot CCW)."""
    x0, y0 = sx, -sy
    rad = math.radians(rot_deg % 360)
    c = round(math.cos(rad))
    s = round(math.sin(rad))
    rx = x0 * c + y0 * s
    ry = -x0 * s + y0 * c
    return (round(cx + rx, 4), round(cy + ry, 4))


class SchematicBuilder:
    def __init__(self, sym_infos: dict[str, dict], comp_map: dict[str, dict], root_uuid: str):
        self.sym_infos = sym_infos
        self.comp_map = comp_map
        self.root_uuid = root_uuid
        self.instances: list[dict] = []
        self.placed_refs: dict[str, dict] = {}
        self.wires: list[tuple[float, float, float, float]] = []
        self.labels: list[tuple[str, float, float, int]] = []
        self.no_connects: list[tuple[float, float]] = []
        self.texts: list[tuple[str, float, float, float]] = []
        self.pwr_idx = 1
        self.flg_idx = 1

    def place_comp(
        self,
        ref: str,
        cx: float,
        cy: float,
        rot: int = 0,
        ref_dx: float | None = None,
        ref_dy: float | None = None,
        val_dx: float | None = None,
        val_dy: float | None = None,
    ) -> dict[str, tuple[float, float]]:
        assert ref not in self.placed_refs, f"Duplicate placement for {ref}"
        assert abs(cx - snap(cx)) < 1e-6 and abs(cy - snap(cy)) < 1e-6, f"Off-grid {ref}: {(cx, cy)}"
        comp = self.comp_map[ref]
        if ref.startswith("TP"):
            lib_id = "adom:TP_0.5mm"
            fp = "adom:Adom_TestPoint_D0.5mm"
        else:
            fp_name = comp["fp"].split(":", 1)[1]
            lib_id = f"PCM_microgoose:{comp['mpn']}"
            fp = f"PCM_microgoose:{fp_name}"
        info = self.sym_infos[lib_id]
        bx0, by0, bx1, by1 = info["bbox"]
        # Transform bbox to sheet
        corners = [
            pin_sheet_xy(bx0, by0, cx, cy, rot),
            pin_sheet_xy(bx0, by1, cx, cy, rot),
            pin_sheet_xy(bx1, by0, cx, cy, rot),
            pin_sheet_xy(bx1, by1, cx, cy, rot),
        ]
        min_x = min(p[0] for p in corners)
        max_x = max(p[0] for p in corners)
        min_y = min(p[1] for p in corners)
        max_y = max(p[1] for p in corners)

        if ref_dx is None or ref_dy is None:
            if rot in (90, 270) and (ref.startswith("R") or ref.startswith("C")) and ref != "R20":
                ref_dx = 3.81
                ref_dy = -1.27
                val_dx = 3.81
                val_dy = 1.27
            else:
                ref_dx = 0.0
                ref_dy = round((min_y - cy) - 2.54, 4)
                val_dx = 0.0
                val_dy = round((max_y - cy) + 2.54, 4)
        if val_dx is None or val_dy is None:
            val_dx = 0.0
            val_dy = round((max_y - cy) + 2.54, 4)

        pin_pts: dict[str, tuple[float, float]] = {}
        for pnum, (px, py, _, _, _) in info["pins"].items():
            pt = pin_sheet_xy(px, py, cx, cy, rot)
            assert abs(pt[0] - snap(pt[0])) < 1e-6 and abs(pt[1] - snap(pt[1])) < 1e-6, (
                f"Off-grid pin {ref}.{pnum}: {pt}"
            )
            pin_pts[pnum] = pt

        rec = {
            "ref": ref,
            "lib_id": lib_id,
            "value": comp["value"],
            "fp": fp,
            "mpn": comp.get("mpn", ""),
            "mfr": comp.get("mfr", ""),
            "cx": cx,
            "cy": cy,
            "rot": rot,
            "ref_xy": (snap(cx + ref_dx), snap(cy + ref_dy)),
            "val_xy": (snap(cx + val_dx), snap(cy + val_dy)),
            "pins": pin_pts,
            "sheet_bbox": (min_x, min_y, max_x, max_y),
            "in_bom": "no" if ref.startswith("TP") else "yes",
            "on_board": "yes",
        }
        self.instances.append(rec)
        self.placed_refs[ref] = rec
        return pin_pts

    def add_power(self, rail: str, x: float, y: float) -> None:
        assert abs(x - snap(x)) < 1e-6 and abs(y - snap(y)) < 1e-6, f"Off-grid power {rail}: {(x, y)}"
        ref = f"#PWR{self.pwr_idx:04d}"
        self.pwr_idx += 1
        lib_id = f"MicrogoosePower:{rail}"
        val_dy = 5.08 if rail == "GND" else -3.81
        rec = {
            "ref": ref,
            "lib_id": lib_id,
            "value": rail,
            "fp": "",
            "mpn": "",
            "mfr": "",
            "cx": x,
            "cy": y,
            "rot": 0,
            "ref_xy": (x, snap(y + val_dy)),
            "val_xy": (x, snap(y + val_dy)),
            "pins": {"1": (x, y)},
            "sheet_bbox": (x - 1.27, y - 2.54, x + 1.27, y + 2.54),
            "in_bom": "no",
            "on_board": "no",
            "hide_ref": True,
        }
        self.instances.append(rec)

    def add_pwr_flag(self, x: float, y: float) -> None:
        assert abs(x - snap(x)) < 1e-6 and abs(y - snap(y)) < 1e-6
        ref = f"#FLG{self.flg_idx:04d}"
        self.flg_idx += 1
        rec = {
            "ref": ref,
            "lib_id": "MicrogoosePower:PWR_FLAG",
            "value": "PWR_FLAG",
            "fp": "",
            "mpn": "",
            "mfr": "",
            "cx": x,
            "cy": y,
            "rot": 0,
            "ref_xy": (x, snap(y - 3.81)),
            "val_xy": (x, snap(y - 3.81)),
            "pins": {"1": (x, y)},
            "sheet_bbox": (x - 1.27, y - 2.54, x + 1.27, y),
            "in_bom": "no",
            "on_board": "no",
            "hide_ref": True,
        }
        self.instances.append(rec)

    def wire(self, x1: float, y1: float, x2: float, y2: float) -> None:
        x1, y1, x2, y2 = round(x1, 4), round(y1, 4), round(x2, 4), round(y2, 4)
        if abs(x1 - x2) < 1e-6 and abs(y1 - y2) < 1e-6:
            return
        assert abs(x1 - x2) < 1e-6 or abs(y1 - y2) < 1e-6, f"Non-orthogonal wire: {(x1, y1)} -> {(x2, y2)}"
        for v in (x1, y1, x2, y2):
            assert abs(v - snap(v)) < 1e-6, f"Off-grid wire coord {v}"
        self.wires.append((x1, y1, x2, y2))

    def wire_chain(self, pts: list[tuple[float, float]]) -> None:
        for (x1, y1), (x2, y2) in zip(pts, pts[1:]):
            self.wire(x1, y1, x2, y2)

    def power_stub_up(self, pt: tuple[float, float], rail: str, dy: float = 3.81) -> None:
        x, y = pt
        yt = snap(y - dy)
        self.wire(x, y, x, yt)
        self.add_power(rail, x, yt)

    def gnd_stub_down(self, pt: tuple[float, float], dy: float = 3.81) -> None:
        x, y = pt
        yb = snap(y + dy)
        self.wire(x, y, x, yb)
        self.add_power("GND", x, yb)

    def label(self, net: str, x: float, y: float, rot: int = 0) -> None:
        assert abs(x - snap(x)) < 1e-6 and abs(y - snap(y)) < 1e-6, f"Off-grid label {net}: {(x, y)}"
        self.labels.append((net, round(x, 4), round(y, 4), rot))

    def stub_label_left(self, pt: tuple[float, float], net: str, dx: float = 6.35) -> None:
        x, y = pt
        xl = snap(x - dx)
        self.wire(xl, y, x, y)
        self.label(net, xl, y, 180)

    def stub_label_right(self, pt: tuple[float, float], net: str, dx: float = 6.35) -> None:
        x, y = pt
        xr = snap(x + dx)
        self.wire(x, y, xr, y)
        self.label(net, xr, y, 0)

    def nc(self, pt: tuple[float, float]) -> None:
        self.no_connects.append((round(pt[0], 4), round(pt[1], 4)))

    def section_title(self, text: str, x: float, y: float, font_mm: float = 2.54) -> None:
        self.texts.append((text, snap(x), snap(y), font_mm))

    def finalize_wires_and_junctions(self) -> tuple[list[tuple[float, float, float, float]], list[tuple[float, float]]]:
        """Split collinear wires at any T-tap / pin / label point and compute exact junctions."""
        special_pts: set[tuple[float, float]] = set()
        pin_count_at: dict[tuple[float, float], int] = defaultdict(int)
        for inst in self.instances:
            for pxy in inst["pins"].values():
                pt = (round(pxy[0], 4), round(pxy[1], 4))
                special_pts.add(pt)
                pin_count_at[pt] += 1
        for _, lx, ly, _ in self.labels:
            special_pts.add((round(lx, 4), round(ly, 4)))
        for x1, y1, x2, y2 in self.wires:
            special_pts.add((round(x1, 4), round(y1, 4)))
            special_pts.add((round(x2, 4), round(y2, 4)))
        # Also include orthogonal wire crossings ONLY if an endpoint lands on the other wire
        # (handled because all endpoints are already in special_pts!)

        # Merge overlapping collinear wire intervals first, then split at special_pts
        horiz: dict[float, list[tuple[float, float]]] = defaultdict(list)
        vert: dict[float, list[tuple[float, float]]] = defaultdict(list)
        for x1, y1, x2, y2 in self.wires:
            if abs(y1 - y2) < 1e-6:
                a, b = min(x1, x2), max(x1, x2)
                horiz[round(y1, 4)].append((a, b))
            else:
                a, b = min(y1, y2), max(y1, y2)
                vert[round(x1, 4)].append((a, b))

        def merge_intervals(ivs: list[tuple[float, float]]) -> list[tuple[float, float]]:
            if not ivs:
                return []
            ivs = sorted(ivs)
            merged = [ivs[0]]
            for s, e in ivs[1:]:
                ps, pe = merged[-1]
                if s <= pe + 1e-6:
                    merged[-1] = (ps, max(pe, e))
                else:
                    merged.append((s, e))
            return merged

        split_wires: list[tuple[float, float, float, float]] = []
        for y, ivs in sorted(horiz.items()):
            for a, b in merge_intervals(ivs):
                cuts = sorted(
                    {a, b}
                    | {px for (px, py) in special_pts if abs(py - y) < 1e-6 and a - 1e-6 <= px <= b + 1e-6}
                )
                for c0, c1 in zip(cuts, cuts[1:]):
                    if c1 - c0 > 1e-6:
                        split_wires.append((round(c0, 4), y, round(c1, 4), y))

        for x, ivs in sorted(vert.items()):
            for a, b in merge_intervals(ivs):
                cuts = sorted(
                    {a, b}
                    | {py for (px, py) in special_pts if abs(px - x) < 1e-6 and a - 1e-6 <= py <= b + 1e-6}
                )
                for c0, c1 in zip(cuts, cuts[1:]):
                    if c1 - c0 > 1e-6:
                        split_wires.append((x, round(c0, 4), x, round(c1, 4)))

        deg: dict[tuple[float, float], int] = defaultdict(int)
        for x1, y1, x2, y2 in split_wires:
            deg[(x1, y1)] += 1
            deg[(x2, y2)] += 1

        junctions: list[tuple[float, float]] = []
        all_pts = set(deg.keys()) | set(pin_count_at.keys())
        for pt in sorted(all_pts):
            total_conn = deg[pt] + pin_count_at[pt]
            if deg[pt] >= 3 or (deg[pt] >= 2 and pin_count_at[pt] >= 1) or pin_count_at[pt] >= 3:
                junctions.append(pt)
        return split_wires, junctions


def build_all() -> None:
    LIB_DIR.mkdir(parents=True, exist_ok=True)
    netlist = json.loads(NETLIST_PATH.read_text())
    calcs = json.loads(CALCS_PATH.read_text())
    comp_map = {c["ref"]: c for c in netlist["components"]}

    # 1. Build snapped PCM_microgoose.kicad_sym
    raw_pcm = PCM_STAGE_SYM.read_text()
    pcm_syms = extract_top_symbols(raw_pcm)
    snapped_pcm_syms: dict[str, str] = {}
    for name, block in pcm_syms.items():
        snapped_pcm_syms[name] = snap_symbol_pins(block)

    pcm_lib_out = ['(kicad_symbol_lib (version 20241209) (generator "adom_aiflow")']
    for block in snapped_pcm_syms.values():
        pcm_lib_out.append("  " + block)
    pcm_lib_out.append(")\n")
    (LIB_DIR / "PCM_microgoose.kicad_sym").write_text("\n".join(pcm_lib_out))

    # 2. Build adom.kicad_sym (TP_0.5mm with lowercase adom:Adom_TestPoint_D0.5mm)
    raw_tp = TP_STAGE_SYM.read_text().replace(
        '"Adom:Adom_TestPoint_D0.5mm"', '"adom:Adom_TestPoint_D0.5mm"'
    )
    (LIB_DIR / "adom.kicad_sym").write_text(raw_tp)
    tp_syms = extract_top_symbols(raw_tp)

    # 3. Build MicrogoosePower.kicad_sym
    pwr_syms = make_power_symbols()
    pwr_lib_out = ['(kicad_symbol_lib (version 20241209) (generator "adom_aiflow")']
    for block in pwr_syms.values():
        pwr_lib_out.append("  " + block)
    pwr_lib_out.append(")\n")
    (LIB_DIR / "MicrogoosePower.kicad_sym").write_text("\n".join(pwr_lib_out))

    # Parse symbol pin & bbox tables
    sym_infos: dict[str, dict] = {}
    embedded_blocks: dict[str, str] = {}
    for name, block in snapped_pcm_syms.items():
        lid = f"PCM_microgoose:{name}"
        sym_infos[lid] = parse_symbol_info(block)
        embedded_blocks[lid] = prefix_lib_symbol(block, "PCM_microgoose", name)
    for name, block in tp_syms.items():
        lid = f"adom:{name}"
        sym_infos[lid] = parse_symbol_info(block)
        embedded_blocks[lid] = prefix_lib_symbol(block, "adom", name)
    for name, block in pwr_syms.items():
        lid = f"MicrogoosePower:{name}"
        sym_infos[lid] = parse_symbol_info(block)
        embedded_blocks[lid] = prefix_lib_symbol(block, "MicrogoosePower", name)

    # Note: R/C vertical orientation helper:
    # At rot=0: pin 1 is at (-3.81, 0), pin 2 is at (+3.81, 0).
    # At rot=270 (CCW): (sx, sy)=(-3.81, 0) -> (x0, y0)=(-3.81, 0), cos=0, sin=-1 -> rx=0, ry=-3.81 -> TOP!
    #                   (sx, sy)=(+3.81, 0) -> rx=0, ry=+3.81 -> BOTTOM!
    # So rot=270 puts pin 1 on TOP (cy - 3.81) and pin 2 on BOTTOM (cy + 3.81)!
    # Let's verify: at rot=90: pin 1 is on BOTTOM (cy + 3.81) and pin 2 is on TOP (cy - 3.81).

    root_uuid = "7b3c9e52-64f1-4a8e-9b14-2c8d5e103f77"
    sb = SchematicBuilder(sym_infos, comp_map, root_uuid)

    # =========================================================================
    # BLOCK 1: MOLECULE CORNERS, BATTERY INPUT & UVLO (x ~ 45..140, y ~ 45..250)
    # =========================================================================
    sb.section_title("1. MOLECULE PINS & CONTACTS", g(34), g(28), font_mm=2.032)

    # MP1..MP4 (MachinePinLargeShort: pin 1 at (+5.08, 0) at rot=0)
    for idx, ref in enumerate(("MP1", "MP2", "MP3", "MP4")):
        py = g(42 + idx * 8)
        pts = sb.place_comp(ref, g(42), py, rot=0, ref_dx=-2.54, ref_dy=-3.81, val_dx=-2.54, val_dy=3.81)
        sb.wire(pts["1"][0], pts["1"][1], g(50), py)
    sb.wire(g(50), g(42), g(50), g(66))
    sb.gnd_stub_down((g(50), g(66)), dy=3.81)

    # MC3, MC5, MC9 (GND contacts)
    for idx, ref in enumerate(("MC3", "MC5", "MC9")):
        py = g(82 + idx * 8)
        pts = sb.place_comp(ref, g(42), py, rot=0, ref_dx=-2.54, ref_dy=-3.81, val_dx=-2.54, val_dy=3.81)
        sb.wire(pts["1"][0], pts["1"][1], g(50), py)
    sb.wire(g(50), g(82), g(50), g(98))
    sb.gnd_stub_down((g(50), g(98)), dy=3.81)
    # PWR_FLAG on GND
    sb.wire(g(50), g(90), g(56), g(90))
    sb.add_pwr_flag(g(56), g(90))

    # MC4 (5V_BUS contact) & MC10 (3V3 contact)
    p_mc4 = sb.place_comp("MC4", g(42), g(116), rot=0, ref_dx=-2.54, ref_dy=-3.81, val_dx=-2.54, val_dy=3.81)
    sb.wire(p_mc4["1"][0], p_mc4["1"][1], g(52), g(116))
    sb.power_stub_up((g(52), g(116)), "5V_BUS", dy=3.81)

    p_mc10 = sb.place_comp("MC10", g(42), g(130), rot=0, ref_dx=-2.54, ref_dy=-3.81, val_dx=-2.54, val_dy=3.81)
    sb.wire(p_mc10["1"][0], p_mc10["1"][1], g(52), g(130))
    sb.power_stub_up((g(52), g(130)), "3V3", dy=3.81)

    # MC6 (SWDIO), MC7 (SWCLK), MC8 (NRST)
    for idx, (ref, net) in enumerate((("MC6", "SWDIO"), ("MC7", "SWCLK"), ("MC8", "NRST"))):
        py = g(146 + idx * 8)
        pts = sb.place_comp(ref, g(42), py, rot=0, ref_dx=-2.54, ref_dy=-3.81, val_dx=-2.54, val_dy=3.81)
        sb.stub_label_right(pts["1"], net, dx=7.62)

    # =========================================================================
    # BLOCK 2: 5V 4A SYNCHRONOUS BUCK (LMR33640DDDAR, 400 kHz) (x ~ 80..265, y ~ 40..175)
    # =========================================================================
    sb.section_title("2. 5.0V 4A SYNCHRONOUS BUCK (LMR33640DDDAR, 400 kHz)", g(84), g(28), font_mm=2.032)

    # MC1, MC2 feeding VBAT bus directly into C1..C4, R5/R6 UVLO, and U1.VIN!
    p_mc1 = sb.place_comp("MC1", g(78), g(50), rot=0, ref_dx=-2.54, ref_dy=-3.81, val_dx=-2.54, val_dy=3.81)
    p_mc2 = sb.place_comp("MC2", g(78), g(58), rot=0, ref_dx=-2.54, ref_dy=-3.81, val_dx=-2.54, val_dy=3.81)
    vbat_y = g(50)
    sb.wire(p_mc1["1"][0], p_mc1["1"][1], g(86), vbat_y)
    sb.wire(p_mc2["1"][0], p_mc2["1"][1], g(86), g(58))
    sb.wire(g(86), vbat_y, g(86), g(58))
    sb.power_stub_up((g(88), vbat_y), "VBAT", dy=3.81)
    sb.add_pwr_flag(g(92), vbat_y)

    # Input capacitor bank C1..C4 (rot=270: pin 1 top, pin 2 bottom)
    cap_cy = g(60)
    for idx, cref in enumerate(("C1", "C2", "C3", "C4")):
        cx = g(96 + idx * 8)
        cp = sb.place_comp(cref, cx, cap_cy, rot=270)
        sb.wire(cx, vbat_y, cp["1"][0], cp["1"][1])
        sb.wire(cp["2"][0], cp["2"][1], cx, g(68))
    sb.wire(g(96), g(68), g(120), g(68))
    sb.gnd_stub_down((g(108), g(68)), dy=3.81)

    # UVLO divider R5 (top, 150k) & R6 (bot, 47k) at x = g(130)
    uvlo_x = g(130)
    p_r5 = sb.place_comp("R5", uvlo_x, g(58), rot=270)
    p_r6 = sb.place_comp("R6", uvlo_x, g(72), rot=270)
    sb.wire(uvlo_x, vbat_y, p_r5["1"][0], p_r5["1"][1])
    # U1 LMR33640DDDAR at (g(156), g(65)):
    # Left pins (x = cx - 14*1.27 = g(142)):
    #   pin 1 PGND: cy - 4g = g(61)
    #   pin 2 VIN:  cy - 2g = g(63)
    #   pin 3 EN:   cy      = g(65)
    #   pin 4 PG:   cy + 2g = g(67)
    #   pin 5 FB:   cy + 4g = g(69)
    # Right pins (x = cx + 14*1.27 = g(170)):
    #   pin 9 AGND: cy - 2g = g(63)
    #   pin 8 SW:   cy      = g(65)
    #   pin 7 BOOT: cy + 2g = g(67)
    #   pin 6 VCC:  cy + 4g = g(69)
    p_u1 = sb.place_comp("U1", g(156), g(65), rot=0)
    # Wire VBAT rail across from g(86) to g(136), down to U1.2 (VIN at y=g(63))
    sb.wire(g(86), vbat_y, g(136), vbat_y)
    sb.wire(g(136), vbat_y, g(136), g(63))
    sb.wire(g(136), g(63), p_u1["2"][0], p_u1["2"][1])

    # U1.1 PGND inverted-U hook to GND stub
    sb.wire_chain([p_u1["1"], (g(140), g(61)), (g(140), g(55)), (g(138), g(55))])
    sb.gnd_stub_down((g(138), g(55)), dy=2.54)

    # Wire BUCK_EN: R5.2 (y=g(61)) -> y=g(65) -> R6.1 (y=g(69)) and across to U1.3 (EN at y=g(65))
    sb.wire(p_r5["2"][0], p_r5["2"][1], p_r6["1"][0], p_r6["1"][1])
    sb.wire(uvlo_x, g(65), p_u1["3"][0], p_u1["3"][1])
    sb.label("BUCK_EN", g(134), g(65), 0)
    sb.gnd_stub_down(p_r6["2"], dy=3.81)

    # U1.4 PG -> BUCK_PG label (goes to U4.16 in Block 5 and R7 pullup in Block 5)
    sb.stub_label_left(p_u1["4"], "BUCK_PG", dx=5.08)

    # U1.9 AGND -> GND via inverted-U hook
    sb.wire_chain([p_u1["9"], (g(172), g(63)), (g(172), g(56)), (g(175), g(56))])
    sb.gnd_stub_down((g(175), g(56)), dy=2.54)

    # U1.7 BOOT -> C5 (rot=0: pin 1 left, pin 2 right) up to SW!
    # Wait: in netlist.json: BUCK_BOOT = [U1.7, C5.1], SW = [U1.8, C5.2, L1.1, TP3.1]
    p_c5 = sb.place_comp("C5", g(182), g(73), rot=0, ref_dx=0.0, ref_dy=3.81, val_dx=0.0, val_dy=6.35)
    sb.wire(p_u1["7"][0], p_u1["7"][1], g(176), g(67))
    sb.wire(g(176), g(67), g(176), g(73))
    sb.wire(g(176), g(73), p_c5["1"][0], p_c5["1"][1])
    sb.label("BUCK_BOOT", g(176), g(73), 0)

    # U1.6 VCC -> C6 (rot=270: pin 1 top, pin 2 bottom) -> GND
    p_c6 = sb.place_comp("C6", g(173), g(82), rot=270)
    sb.wire(p_u1["6"][0], p_u1["6"][1], g(173), g(69))
    sb.wire(g(173), g(69), p_c6["1"][0], p_c6["1"][1])
    sb.label("BUCK_VCC", g(173), g(75), 0)
    sb.gnd_stub_down(p_c6["2"], dy=3.81)

    # U1.8 SW -> L1.1 (74439346047 at (g(196), g(65)): pin 1 at g(192), pin 2 at g(200))
    p_l1 = sb.place_comp("L1", g(196), g(65), rot=0)
    sb.wire(p_u1["8"][0], p_u1["8"][1], p_l1["1"][0], p_l1["1"][1])
    # Connect C5.2 up to SW node at x = g(188)
    sb.wire(p_c5["2"][0], p_c5["2"][1], g(188), g(73))
    sb.wire(g(188), g(65), g(188), g(73))
    sb.label("SW", g(188), g(65), 0)

    # L1.2 -> 5V_RAW node feeding C7, C8 and R20 shunt!
    p_c7 = sb.place_comp("C7", g(206), g(76), rot=270)
    p_c8 = sb.place_comp("C8", g(214), g(76), rot=270)
    p_r20 = sb.place_comp("R20", g(225), g(65), rot=0)
    sb.wire(p_l1["2"][0], p_l1["2"][1], p_r20["1"][0], p_r20["1"][1])
    sb.label("5V_RAW", g(204), g(65), 0)
    for cp in (p_c7, p_c8):
        sb.wire(cp["1"][0], g(65), cp["1"][0], cp["1"][1])
        sb.wire(cp["2"][0], cp["2"][1], cp["2"][0], g(84))
    sb.wire(g(206), g(84), g(214), g(84))
    sb.gnd_stub_down((g(210), g(84)), dy=3.81)

    # R20.2 -> 5V_BUS rail ending cleanly at C11 (g(256)) + PWR_FLAG + feedback divider R1..R4!
    sb.wire(p_r20["2"][0], p_r20["2"][1], g(256), g(65))
    sb.power_stub_up((g(232), g(65)), "5V_BUS", dy=3.81)
    sb.add_pwr_flag(g(236), g(65))

    for idx, cref in enumerate(("C9", "C10", "C11")):
        cx = g(240 + idx * 8)
        cp = sb.place_comp(cref, cx, g(76), rot=270)
        sb.wire(cx, g(65), cp["1"][0], cp["1"][1])
        sb.wire(cp["2"][0], cp["2"][1], cx, g(84))
    sb.wire(g(240), g(84), g(256), g(84))
    sb.gnd_stub_down((g(248), g(84)), dy=3.81)

    # Feedback divider stack at x = g(140) below U1, sensed from 5V_BUS down to FB!
    # R1 (47k): 5V_BUS -> FB_MID
    # R2 (33k): FB_MID -> FB
    # R3 (10k): FB -> FB_BOT_MID
    # R4 (10k): FB_BOT_MID -> GND
    fb_x = g(148)
    p_r1 = sb.place_comp("R1", fb_x, g(86), rot=270)
    p_r2 = sb.place_comp("R2", fb_x, g(98), rot=270)
    p_r3 = sb.place_comp("R3", fb_x, g(112), rot=270)
    p_r4 = sb.place_comp("R4", fb_x, g(124), rot=270)
    sb.power_stub_up(p_r1["1"], "5V_BUS", dy=2.54)
    sb.wire(p_r1["2"][0], p_r1["2"][1], p_r2["1"][0], p_r2["1"][1])
    sb.label("FB_MID", fb_x, g(92), 0)
    sb.wire(p_r2["2"][0], p_r2["2"][1], p_r3["1"][0], p_r3["1"][1])
    # Wire FB node (fb_x, g(105)) left to x=g(138), up to y=g(69), into U1.5!
    sb.wire(g(138), g(105), fb_x, g(105))
    sb.wire(g(138), g(69), g(138), g(105))
    sb.wire(g(138), g(69), p_u1["5"][0], p_u1["5"][1])
    sb.label("FB", g(142), g(105), 0)
    sb.wire(p_r3["2"][0], p_r3["2"][1], p_r4["1"][0], p_r4["1"][1])
    sb.label("FB_BOT_MID", fb_x, g(118), 0)
    sb.gnd_stub_down(p_r4["2"], dy=3.81)

    # =========================================================================
    # BLOCK 3: INA226 SHUNT MONITOR, VBAT ADC DIVIDER & 3.3V LDO (x ~ 180..275, y ~ 105..210)
    # =========================================================================
    sb.section_title("3. INA226 POWER MONITOR, VBAT SENSE & 3.3V LDO", g(180), g(100))

    # U3 INA226AIDGST placed at (g(206), g(124)):
    # Right pins (x = g(220)):
    #   pin 10 IN+:  y = g(120) -> wire directly up to 5V_RAW at x = g(220), y = g(65)!
    #   pin 9  IN-:  y = g(122) -> wire to 5V_BUS at x = g(230), y = g(65)!
    #   pin 8  VBUS: y = g(124) -> wire to 5V_BUS at x = g(230)!
    #   pin 7  GND:  y = g(126)
    #   pin 6  VS:   y = g(128) -> 3V3 + C20
    # Left pins (x = g(192)):
    #   pin 1  A1:    y = g(120) -> GND
    #   pin 2  A0:    y = g(122) -> GND
    #   pin 3  Alert: y = g(124) -> INA_ALERT + R15 pullup to 3V3
    #   pin 4  SDA:   y = g(126) -> I2C_SDA
    #   pin 5  SCL:   y = g(128) -> I2C_SCL
    p_u3 = sb.place_comp("U3", g(206), g(124), rot=0)
    # Wire U3.10 IN+ directly up to R20.1 (5V_RAW at x=g(220), y=g(65))!
    sb.wire(p_u3["10"][0], p_u3["10"][1], g(220), g(65))
    # Wire U3.9 IN- and U3.8 VBUS to x=g(230), up to 5V_BUS at y=g(65)!
    sb.wire(p_u3["9"][0], p_u3["9"][1], g(230), g(122))
    sb.wire(p_u3["8"][0], p_u3["8"][1], g(230), g(124))
    sb.wire(g(230), g(65), g(230), g(124))

    # U3.7 GND
    sb.wire(p_u3["7"][0], p_u3["7"][1], g(224), g(126))
    sb.gnd_stub_down((g(224), g(126)), dy=7.62)

    # U3.6 VS -> 3V3 + C20 decoupling
    p_c20 = sb.place_comp("C20", g(234), g(134), rot=270)
    sb.wire(p_u3["6"][0], p_u3["6"][1], g(234), g(128))
    sb.wire(g(234), g(128), p_c20["1"][0], p_c20["1"][1])
    sb.power_stub_up((g(234), g(128)), "3V3", dy=3.81)
    sb.gnd_stub_down(p_c20["2"], dy=3.81)

    # U3.1 A1 & U3.2 A0 -> GND
    sb.wire(p_u3["1"][0], p_u3["1"][1], g(188), g(120))
    sb.wire(p_u3["2"][0], p_u3["2"][1], g(188), g(122))
    sb.wire(g(188), g(120), g(188), g(122))
    sb.wire(g(188), g(120), g(184), g(120))
    sb.gnd_stub_down((g(184), g(120)), dy=2.54)

    # U3.3 Alert + R15 pullup to 3V3
    p_r15 = sb.place_comp("R15", g(180), g(116), rot=270)
    sb.power_stub_up(p_r15["1"], "3V3", dy=2.54)
    sb.wire(p_r15["2"][0], p_r15["2"][1], g(180), g(124))
    sb.wire(g(174), g(124), p_u3["3"][0], p_u3["3"][1])
    sb.label("INA_ALERT", g(174), g(124), 180)

    # U3.4 SDA & U3.5 SCL
    sb.stub_label_left(p_u3["4"], "I2C_SDA", dx=7.62)
    sb.stub_label_left(p_u3["5"], "I2C_SCL", dx=7.62)

    # VBAT_ADC divider: R11 (100k), R12 (33k), C25 (100n) at x = g(184)..g(194), y ~ g(154)..g(178)
    p_r11 = sb.place_comp("R11", g(184), g(154), rot=270)
    p_r12 = sb.place_comp("R12", g(184), g(168), rot=270)
    p_c25 = sb.place_comp("C25", g(194), g(168), rot=270)
    sb.power_stub_up(p_r11["1"], "VBAT", dy=2.54)
    sb.wire(p_r11["2"][0], p_r11["2"][1], p_r12["1"][0], p_r12["1"][1])
    sb.wire(g(184), g(161), g(202), g(161))
    sb.wire(g(194), g(161), p_c25["1"][0], p_c25["1"][1])
    sb.label("VBAT_ADC", g(202), g(161), 0)
    sb.wire(p_r12["2"][0], p_r12["2"][1], g(184), g(175))
    sb.wire(p_c25["2"][0], p_c25["2"][1], g(194), g(175))
    sb.wire(g(184), g(175), g(194), g(175))
    sb.gnd_stub_down((g(189), g(175)), dy=3.81)

    # U2 AP2114H-3.3TRG1 LDO at (g(246), g(160)):
    # Note: AP2114H pins: 1 GND (-17.78, 0), 2 VOUT (-17.78, -2.54 -> sheet cy+2g), 3 VIN (+17.78, 0)
    p_u2 = sb.place_comp("U2", g(246), g(160), rot=0)
    p_c12 = sb.place_comp("C12", g(266), g(168), rot=270)
    p_c26 = sb.place_comp("C26", g(226), g(170), rot=270)
    # VIN (pin 3 at g(260), g(160)) -> 5V_BUS + C12
    sb.wire(p_u2["3"][0], p_u2["3"][1], g(266), g(160))
    sb.wire(g(266), g(160), p_c12["1"][0], p_c12["1"][1])
    sb.power_stub_up((g(266), g(160)), "5V_BUS", dy=3.81)
    sb.gnd_stub_down(p_c12["2"], dy=3.81)
    # GND (pin 1 at g(232), g(160)) -> GND via inverted-U hook
    sb.wire_chain([p_u2["1"], (g(230), g(160)), (g(230), g(154)), (g(228), g(154))])
    sb.gnd_stub_down((g(228), g(154)), dy=2.54)
    # VOUT (pin 2 at g(232), g(162)) -> 3V3 + C26 (U2.2 is power_out, driving 3V3!)
    sb.wire(p_u2["2"][0], p_u2["2"][1], g(226), g(162))
    sb.wire(g(226), g(162), p_c26["1"][0], p_c26["1"][1])
    sb.power_stub_up((g(226), g(162)), "3V3", dy=3.81)
    sb.gnd_stub_down(p_c26["2"], dy=3.81)

    # =========================================================================
    # BLOCK 4: STM32G431CBT6 SPINE MCU (x ~ 310..420, y ~ 42..155)
    # =========================================================================
    sb.section_title("4. STM32G431CBT6 SPINE MCU (170 MHz CORTEX-M4)", g(310), g(28))

    p_u4 = sb.place_comp("U4", g(356), g(44), rot=0)
    # Unconnected pins on U4 (21 pins)
    for upin in (
        "2", "3", "4", "5", "6", "12", "13", "14", "15",
        "27", "28", "29", "31", "32", "33", "34",
        "39", "40", "41", "42", "46",
    ):
        sb.nc(p_u4[upin])

    # Left-side active pins on U4 (x = g(334)):
    # pin 7 NRST (y = g(60)): R8 (10k pullup to 3V3) + C24 (100n to GND) + NRST label
    nrst_y = p_u4["7"][1]
    p_r8 = sb.place_comp("R8", g(314), snap(nrst_y - g(7)), rot=270)
    p_c24 = sb.place_comp("C24", g(306), snap(nrst_y + g(7)), rot=270)
    sb.power_stub_up(p_r8["1"], "3V3", dy=2.54)
    sb.wire(p_r8["2"][0], p_r8["2"][1], g(314), nrst_y)
    sb.wire(g(300), nrst_y, p_u4["7"][0], p_u4["7"][1])
    sb.wire(g(306), nrst_y, p_c24["1"][0], p_c24["1"][1])
    sb.gnd_stub_down(p_c24["2"], dy=2.54)
    sb.label("NRST", g(300), nrst_y, 180)

    # pin 45 BOOT0 (y = g(62)): R9 (10k pulldown to GND) wired locally + 1 label BOOT0
    boot_y = p_u4["45"][1]
    p_r9 = sb.place_comp("R9", g(322), snap(boot_y + g(6)), rot=270)
    sb.wire(g(322), boot_y, p_u4["45"][0], p_u4["45"][1])
    sb.wire(g(322), boot_y, p_r9["1"][0], p_r9["1"][1])
    sb.label("BOOT0", g(326), boot_y, 0)
    sb.gnd_stub_down(p_r9["2"], dy=2.54)

    # Remaining left-side signal pins on U4:
    for pnum, net in (
        ("8", "VBAT_ADC"),
        ("9", "LED_PWM_3V3"),
        ("10", "HOST_TX"),
        ("11", "HOST_RX"),
        ("38", "SWCLK"),
        ("37", "SWDIO"),
        ("30", "HEAD_INT"),
    ):
        sb.stub_label_left(p_u4[pnum], net, dx=8.89)

    # Right-side power pins on U4 (1, 20, 21, 24, 48, 36 -> 3V3) + C13..C17 decoupling bank!
    vdd_bus_x = g(384)
    vdd_ys = [p_u4[p][1] for p in ("1", "20", "21", "24", "48", "36")]
    for p in ("1", "20", "21", "24", "48", "36"):
        sb.wire(p_u4[p][0], p_u4[p][1], vdd_bus_x, p_u4[p][1])
    sb.wire(vdd_bus_x, min(vdd_ys), vdd_bus_x, max(vdd_ys))
    sb.power_stub_up((vdd_bus_x, min(vdd_ys)), "3V3", dy=3.81)

    # Place C13..C17 decoupling capacitors alongside U4 3V3 rail at y = min(vdd_ys)
    cap_top_y = min(vdd_ys)
    sb.wire(vdd_bus_x, cap_top_y, g(424), cap_top_y)
    for idx, cref in enumerate(("C13", "C14", "C15", "C16", "C17")):
        cx = g(392 + idx * 8)
        cp = sb.place_comp(cref, cx, snap(cap_top_y + g(6)), rot=270)
        sb.wire(cx, cap_top_y, cp["1"][0], cp["1"][1])
        sb.wire(cp["2"][0], cp["2"][1], cx, snap(cap_top_y + g(12)))
    sb.wire(g(392), snap(cap_top_y + g(12)), g(424), snap(cap_top_y + g(12)))
    sb.gnd_stub_down((g(408), snap(cap_top_y + g(12))), dy=3.81)

    # Right-side ground pins on U4 (19, 23, 47, 35 -> GND)
    vss_bus_x = g(384)
    vss_ys = [p_u4[p][1] for p in ("19", "23", "47", "35")]
    for p in ("19", "23", "47", "35"):
        sb.wire(p_u4[p][0], p_u4[p][1], vss_bus_x, p_u4[p][1])
    sb.wire(vss_bus_x, min(vss_ys), vss_bus_x, max(vss_ys))
    sb.gnd_stub_down((vss_bus_x, max(vss_ys)), dy=2.54)

    # Right-side signal pins on U4:
    # 16: BUCK_PG (with R7 10k pullup to 3V3!), 17: IMU_INT1, 18: INA_ALERT,
    # 22: DXL_TX, 44: I2C_SDA, 43: I2C_SCL, 26: DXL_DIR, 25: DXL_RX
    pg_y = p_u4["16"][1]
    p_r7 = sb.place_comp("R7", g(396), snap(pg_y - g(5)), rot=270)
    sb.power_stub_up(p_r7["1"], "3V3", dy=2.54)
    sb.wire(p_r7["2"][0], p_r7["2"][1], g(396), pg_y)
    sb.wire(p_u4["16"][0], pg_y, g(404), pg_y)
    sb.label("BUCK_PG", g(404), pg_y, 0)

    for pnum, net in (
        ("17", "IMU_INT1"),
        ("18", "INA_ALERT"),
        ("22", "DXL_TX"),
        ("44", "I2C_SDA"),
        ("43", "I2C_SCL"),
        ("26", "DXL_DIR"),
        ("25", "DXL_RX"),
    ):
        sb.stub_label_right(p_u4[pnum], net, dx=8.89)

    # =========================================================================
    # BLOCK 5: BMI270 6-AXIS TORSO IMU & I2C PULL-UPS (x ~ 460..540, y ~ 40..110)
    # =========================================================================
    sb.section_title("5. BMI270 TORSO IMU & 400 kHz I2C PULL-UPS", g(456), g(28))

    p_u5 = sb.place_comp("U5", g(486), g(68), rot=0, ref_dx=-10.16, ref_dy=-15.24, val_dx=8.89, val_dy=-15.24)
    # U5 pin 9 (INT2) unconnected
    sb.nc(p_u5["9"])
    # Top pins: 8 VDD (x=g(486), y=g(56)), 5 VDDIO (x=g(490), y=g(56)) -> 3V3 + C18, C19 placed cleanly above
    sb.wire(p_u5["8"][0], p_u5["8"][1], p_u5["8"][0], g(42))
    sb.wire(p_u5["5"][0], p_u5["5"][1], p_u5["5"][0], g(42))
    sb.wire(g(486), g(42), g(514), g(42))
    sb.power_stub_up((g(488), g(42)), "3V3", dy=2.54)
    for idx, cref in enumerate(("C18", "C19")):
        cx = g(506 + idx * 8)
        cp = sb.place_comp(cref, cx, g(48), rot=270)
        sb.wire(cx, g(42), cp["1"][0], cp["1"][1])
        sb.wire(cp["2"][0], cp["2"][1], cx, g(54))
    sb.wire(g(506), g(54), g(514), g(54))
    sb.gnd_stub_down((g(510), g(54)), dy=2.54)

    # Bottom pins: 7 GND (g(486), g(80)), 6 GNDIO (g(490), g(80)) -> GND
    sb.wire(p_u5["7"][0], p_u5["7"][1], p_u5["7"][0], g(84))
    sb.wire(p_u5["6"][0], p_u5["6"][1], p_u5["6"][0], g(84))
    sb.wire(g(486), g(84), g(490), g(84))
    sb.gnd_stub_down((g(488), g(84)), dy=2.54)

    # Left pins of U5 (x = g(474)):
    #   12 ~CSB (y=g(64)) -> 3V3, 10 ~OCSB (y=g(74)) -> 3V3
    #   1 SDO (y=g(66)), 2 ASDX (y=g(70)), 3 ASCX (y=g(72)), 11 OSDO (y=g(76)) -> GND
    sb.wire(p_u5["12"][0], p_u5["12"][1], g(464), p_u5["12"][1])
    sb.wire(p_u5["10"][0], p_u5["10"][1], g(464), p_u5["10"][1])
    sb.wire(g(464), p_u5["12"][1], g(464), p_u5["10"][1])
    sb.power_stub_up((g(464), p_u5["12"][1]), "3V3", dy=3.81)

    for gp in ("1", "2", "3", "11"):
        sb.wire(p_u5[gp][0], p_u5[gp][1], g(470), p_u5[gp][1])
    sb.wire(g(470), p_u5["1"][1], g(470), p_u5["11"][1])
    sb.gnd_stub_down((g(470), p_u5["11"][1]), dy=3.81)

    # Right pins of U5 (x = g(498)):
    #   14 SDA (y=g(64)) + R17 (4k7 to 3V3), 13 SCL (y=g(66)) + R16 (4k7 to 3V3), 4 INT1 (y=g(70))
    p_r17 = sb.place_comp("R17", g(522), g(56), rot=270)
    p_r16 = sb.place_comp("R16", g(530), g(56), rot=270)
    sb.power_stub_up(p_r17["1"], "3V3", dy=2.54)
    sb.power_stub_up(p_r16["1"], "3V3", dy=2.54)
    sb.wire(p_u5["14"][0], p_u5["14"][1], g(536), p_u5["14"][1])
    sb.wire(p_r17["2"][0], p_r17["2"][1], g(522), p_u5["14"][1])
    sb.label("I2C_SDA", g(536), p_u5["14"][1], 0)

    sb.wire(p_u5["13"][0], p_u5["13"][1], g(536), p_u5["13"][1])
    sb.wire(p_r16["2"][0], p_r16["2"][1], g(530), p_u5["13"][1])
    sb.label("I2C_SCL", g(536), p_u5["13"][1], 0)

    sb.stub_label_right(p_u5["4"], "IMU_INT1", dx=7.62)

    # =========================================================================
    # BLOCK 6: 1 Mbps DYNAMIXEL HALF-DUPLEX TRANSCEIVER & LED INDICATORS (x ~ 456..555, y ~ 110..210)
    # =========================================================================
    sb.section_title("6. 1 Mbps DYNAMIXEL BUS & STATUS LEDS", g(456), g(98), font_mm=2.032)

    # U6 SN74LVC1G126DBVR at (g(486), g(124)):
    # Left (x=g(472)): 1 OE (y=g(122)), 2 A (y=g(124)), 3 GND (y=g(126))
    # Right (x=g(500)): 5 VCC (y=g(124)), 4 Y (y=g(126))
    p_u6 = sb.place_comp("U6", g(486), g(124), rot=0)
    p_r10 = sb.place_comp("R10", g(466), g(132), rot=270)
    sb.wire(g(458), g(122), p_u6["1"][0], p_u6["1"][1])
    sb.wire(g(466), g(122), p_r10["1"][0], p_r10["1"][1])
    sb.gnd_stub_down(p_r10["2"], dy=2.54)
    sb.label("DXL_DIR", g(458), g(122), 180)

    sb.stub_label_left(p_u6["2"], "DXL_TX", dx=10.16)
    sb.wire(p_u6["3"][0], p_u6["3"][1], g(470), g(126))
    sb.gnd_stub_down((g(470), g(126)), dy=3.81)

    # U6.5 VCC + C21 (100n) -> 3V3
    p_c21 = sb.place_comp("C21", g(506), g(116), rot=270)
    sb.wire(p_u6["5"][0], p_u6["5"][1], g(502), g(124))
    sb.wire(g(502), g(110), g(502), g(124))
    sb.wire(g(502), g(110), g(506), g(110))
    sb.wire(g(506), g(110), p_c21["1"][0], p_c21["1"][1])
    sb.power_stub_up((g(502), g(110)), "3V3", dy=2.54)
    sb.gnd_stub_down(p_c21["2"], dy=2.54)

    # U6.4 Y -> DXL_DATA with R14 (10k pullup to 3V3) and R18 (100R series to DXL_RX)!
    p_r14 = sb.place_comp("R14", g(516), g(118), rot=270)
    p_r18 = sb.place_comp("R18", g(516), g(134), rot=0)  # pin 1 left (DXL_RX), pin 2 right (DXL_DATA)
    sb.power_stub_up(p_r14["1"], "3V3", dy=2.54)
    sb.wire(p_u6["4"][0], p_u6["4"][1], g(528), g(126))
    sb.wire(p_r14["2"][0], p_r14["2"][1], g(516), g(126))
    sb.wire(p_r18["2"][0], p_r18["2"][1], g(522), g(134))
    sb.wire(g(522), g(126), g(522), g(134))
    sb.label("DXL_DATA", g(528), g(126), 0)
    sb.stub_label_left(p_r18["1"], "DXL_RX", dx=7.62)

    # 5V Power-Good LED: R13 (1k) + D1 (IN-S63BTG: pin 2 A left, pin 1 K right)
    p_r13 = sb.place_comp("R13", g(466), g(154), rot=0)
    p_d1 = sb.place_comp("D1", g(482), g(154), rot=0)
    sb.wire(g(460), g(154), p_r13["1"][0], p_r13["1"][1])
    sb.power_stub_up((g(460), g(154)), "5V_BUS", dy=3.81)
    sb.wire(p_r13["2"][0], p_r13["2"][1], p_d1["2"][0], p_d1["2"][1])
    sb.label("PG_LED_A", g(474), g(154), 0)
    sb.wire(p_d1["1"][0], p_d1["1"][1], g(490), g(154))
    sb.gnd_stub_down((g(490), g(154)), dy=3.81)

    # Addressable RGB Status Pixel: U7 (SN74AHCT1G125DBVR) + C22 + R19 (100R) + D2 (WS2812B-2020) + C23
    # U7 at (g(478), g(176)):
    #   1 ~OE (g(464), g(174)) -> GND
    #   2 A   (g(464), g(176)) -> LED_PWM_3V3
    #   3 GND (g(464), g(178)) -> GND
    #   5 VCC (g(492), g(176)) -> 5V_BUS + C22
    #   4 Y   (g(492), g(178)) -> LED_DIN_BUF -> R19.1, R19.2 -> LED_DIN -> D2.3
    p_u7 = sb.place_comp("U7", g(478), g(176), rot=0)
    sb.wire(p_u7["1"][0], p_u7["1"][1], g(460), g(174))
    sb.wire(p_u7["3"][0], p_u7["3"][1], g(460), g(178))
    sb.wire(g(460), g(174), g(460), g(178))
    sb.gnd_stub_down((g(460), g(178)), dy=3.81)
    sb.stub_label_left(p_u7["2"], "LED_PWM_3V3", dx=10.16)

    p_c22 = sb.place_comp("C22", g(498), g(168), rot=270)
    sb.wire(p_u7["5"][0], p_u7["5"][1], g(494), g(176))
    sb.wire(g(494), g(162), g(494), g(176))
    sb.wire(g(494), g(162), g(498), g(162))
    sb.wire(g(498), g(162), p_c22["1"][0], p_c22["1"][1])
    sb.power_stub_up((g(494), g(162)), "5V_BUS", dy=2.54)
    sb.gnd_stub_down(p_c22["2"], dy=2.54)

    # D2 WS2812B-2020 at (g(528), g(176)):
    #   pin 3 DI:  (cx - 14g, cy + 2g) = (g(514), g(178))! Matches U7.4 Y height g(178)!!
    #   pin 1 DO:  (g(514), g(180)) -> NC
    #   pin 2 GND: (g(514), g(186)) -> GND
    #   pin 4 VDD: (g(542), g(178)) -> 5V_BUS + C23
    p_r19 = sb.place_comp("R19", g(504), g(178), rot=0)
    p_d2 = sb.place_comp("D2", g(528), g(176), rot=0)
    sb.wire(p_u7["4"][0], p_u7["4"][1], p_r19["1"][0], p_r19["1"][1])
    sb.label("LED_DIN_BUF", g(497), g(178), 0)
    sb.wire(p_r19["2"][0], p_r19["2"][1], p_d2["3"][0], p_d2["3"][1])
    sb.label("LED_DIN", g(510), g(178), 0)
    sb.nc(p_d2["1"])
    sb.wire(p_d2["2"][0], p_d2["2"][1], g(510), p_d2["2"][1])
    sb.gnd_stub_down((g(510), p_d2["2"][1]), dy=3.81)

    p_c23 = sb.place_comp("C23", g(548), g(184), rot=270)
    sb.wire(p_d2["4"][0], p_d2["4"][1], g(548), p_d2["4"][1])
    sb.wire(g(548), p_d2["4"][1], p_c23["1"][0], p_c23["1"][1])
    sb.power_stub_up((g(548), p_d2["4"][1]), "5V_BUS", dy=3.81)
    sb.gnd_stub_down(p_c23["2"], dy=3.81)

    # =========================================================================
    # BLOCK 7: JST-GH HARNESS CONNECTORS J1..J5 (x ~ 575..640, y ~ 40..205)
    # =========================================================================
    sb.section_title("7. JST-GH CONNECTORS (J1..J5)", g(568), g(28), font_mm=2.032)

    # J1, J2, J3 (BM03B-GHS-TBT) + C27, C28, C29 (10u bulk decoupling on 5V_BUS)
    # BM03B pins at rot=0: 1 (-5g, -2g), 2 (-5g, 0), 3 (-5g, +2g), MP (0, +6g)
    # All three share DXL_DATA -> tie their pin 3 stubs onto a vertical DXL_DATA bus at x = g(578)
    # with ONE label "DXL_DATA" so there are zero short-hop labels!
    dxl_bus_x = g(578)
    j_ys = (g(48), g(72), g(96))
    for jref, cref, jy in zip(("J1", "J2", "J3"), ("C27", "C28", "C29"), j_ys):
        pj = sb.place_comp(jref, g(604), jy, rot=0)
        pc = sb.place_comp(cref, g(590), snap(jy + g(4)), rot=270)
        # Pin 1 -> GND via inverted-U hook
        sb.wire_chain([pj["1"], (g(596), pj["1"][1]), (g(596), snap(jy - g(6))), (g(594), snap(jy - g(6)))])
        sb.gnd_stub_down((g(594), snap(jy - g(6))), dy=2.54)
        # Pin 2 -> 5V_BUS + bulk cap
        sb.wire(pj["2"][0], pj["2"][1], g(590), pj["2"][1])
        sb.wire(g(590), pj["2"][1], pc["1"][0], pc["1"][1])
        sb.power_stub_up((g(590), pj["2"][1]), "5V_BUS", dy=3.81)
        sb.gnd_stub_down(pc["2"], dy=2.54)
        # Pin 3 -> DXL_DATA bus at dxl_bus_x
        sb.wire(dxl_bus_x, pj["3"][1], pj["3"][0], pj["3"][1])
        # Pin MP -> GND
        sb.gnd_stub_down(pj["MP"], dy=2.54)

    sb.wire(dxl_bus_x, snap(j_ys[0] + g(2)), dxl_bus_x, snap(j_ys[2] + g(2)))
    sb.wire(g(572), snap(j_ys[1] + g(2)), dxl_bus_x, snap(j_ys[1] + g(2)))
    sb.label("DXL_DATA", g(572), snap(j_ys[1] + g(2)), 180)

    # J4 RADXA_LINK (BM05B-GHS-TBT) at (g(604), g(130)):
    # Pins: 1 (-5g, -4g): 5V_BUS, 2 (-5g, -2g): 5V_BUS, 3 (-5g, 0): GND,
    #       4 (-5g, +2g): HOST_TX, 5 (-5g, +4g): HOST_RX, MP (0, +8g): GND
    p_j4 = sb.place_comp("J4", g(604), g(130), rot=0)
    sb.wire(p_j4["1"][0], p_j4["1"][1], g(594), p_j4["1"][1])
    sb.wire(p_j4["2"][0], p_j4["2"][1], g(594), p_j4["2"][1])
    sb.wire(g(594), p_j4["1"][1], g(594), p_j4["2"][1])
    sb.power_stub_up((g(594), p_j4["1"][1]), "5V_BUS", dy=2.54)
    sb.wire(p_j4["3"][0], p_j4["3"][1], g(576), p_j4["3"][1])
    sb.gnd_stub_down((g(576), p_j4["3"][1]), dy=2.54)
    sb.stub_label_left(p_j4["4"], "HOST_TX", dx=7.62)
    sb.stub_label_left(p_j4["5"], "HOST_RX", dx=7.62)
    sb.gnd_stub_down(p_j4["MP"], dy=2.54)

    # J5 HEAD_I2C (BM05B-GHS-TBT) at (g(604), g(168)):
    # Pins: 1: 3V3, 2: GND, 3: I2C_SCL, 4: I2C_SDA, 5: HEAD_INT, MP: GND
    p_j5 = sb.place_comp("J5", g(604), g(168), rot=0)
    sb.wire(p_j5["1"][0], p_j5["1"][1], g(594), p_j5["1"][1])
    sb.power_stub_up((g(594), p_j5["1"][1]), "3V3", dy=2.54)
    sb.wire(p_j5["2"][0], p_j5["2"][1], g(576), p_j5["2"][1])
    sb.gnd_stub_down((g(576), p_j5["2"][1]), dy=2.54)
    sb.stub_label_left(p_j5["3"], "I2C_SCL", dx=7.62)
    sb.stub_label_left(p_j5["4"], "I2C_SDA", dx=7.62)
    sb.stub_label_left(p_j5["5"], "HEAD_INT", dx=7.62)
    sb.gnd_stub_down(p_j5["MP"], dy=2.54)

    # =========================================================================
    # BLOCK 8: WORKCELL PROBE TEST POINTS TP1..TP9 (x ~ 575..635, y ~ 205..320)
    # =========================================================================
    sb.section_title("8. WORKCELL TEST POINTS (TP1..TP9)", g(568), g(198), font_mm=2.032)

    # TP_0.5mm has pin 1 at (0, 0) pointing up into circle at y = -3.302 on sheet (rot=0).
    # Let's wire downward/left from (cx, cy)!
    tp_specs = [
        ("TP1", "VBAT", True),
        ("TP2", "BUCK_EN", False),
        ("TP3", "SW", False),
        ("TP4", "5V_BUS", True),
        ("TP5", "FB", False),
        ("TP6", "3V3", True),
        ("TP7", "DXL_DATA", False),
        ("TP8", "I2C_SCL", False),
        ("TP9", "I2C_SDA", False),
    ]
    for idx, (tpref, net, is_power) in enumerate(tp_specs):
        col = idx % 3
        row = idx // 3
        tx = g(580 + col * 18)
        ty = g(214 + row * 16)
        ptp = sb.place_comp(
            tpref, tx, ty, rot=0, ref_dx=3.81, ref_dy=-5.08, val_dx=3.81, val_dy=-2.54
        )
        sb.wire(tx, ty, tx, snap(ty + g(3)))
        if is_power:
            sb.wire(tx, snap(ty + g(3)), snap(tx - g(4)), snap(ty + g(3)))
            sb.power_stub_up((snap(tx - g(4)), snap(ty + g(3))), net, dy=2.54)
        else:
            sb.wire(snap(tx - g(6)), snap(ty + g(3)), tx, snap(ty + g(3)))
            sb.label(net, snap(tx - g(6)), snap(ty + g(3)), 180)

    # =========================================================================
    # BLOCK 9: DESIGN CALCULATIONS & OPERATING ENVELOPE NOTE (empty lower-left!)
    # =========================================================================
    note_lines = [
        "MICROGOOSE SPINE REV A - DESIGN SUMMARY (from design/calcs.json)",
        f"1. Battery Input (VBAT): 2S NP-F550 Li-ion, {calcs['vin_min']:.1f} V to {calcs['vin_max']:.1f} V ({calcs['vin_nom']:.1f} V nom) via MC1/MC2.",
        f"2. 5V 4A Sync Buck (U1 LMR33640DDDAR, fSW = {calcs['fsw_kHz']:.0f} kHz, L1 = 4.7 uH WE-XHMI):",
        f"   - Feedback R1+R2 = 80 kOhm / R3+R4 = 20 kOhm -> VOUT = {calcs['buck5v']['voutNomV']:.2f} V (worst-case {calcs['buck5v']['voutRangeWorstCaseV'][0]:.3f}..{calcs['buck5v']['voutRangeWorstCaseV'][1]:.3f} V).",
        f"   - UVLO R5 = 150 kOhm / R6 = 47 kOhm -> V_rise = {calcs['buck5v']['uvloRiseTypV']:.2f} V typ, V_fall = {calcs['buck5v']['uvloFallTypV']:.2f} V typ.",
        f"   - Cout = 4x 22 uF 0805 X5R ({calcs['buck5v']['cOutEffectiveUf']:.1f} uF eff at 5V), ripple = {calcs['buck5v']['rippleWorstCaseMvPp']:.1f} mVpp worst-case.",
        f"3. Shunt & Telemetry (R20 + U3 INA226, I2C 0x40): 0.30 mOhm 1% Kelvin shunt ({calcs['telemetry']['vShuntAt4AMv']:.2f} mV at 4.0 A).",
        f"4. Logic Rail (U2 AP2114H-3.3TRG1): 3.30 V ({calcs['ldo3v3']['voutRangeV'][0]:.2f}..{calcs['ldo3v3']['voutRangeV'][1]:.2f} V) for STM32G431CBT6, BMI270 (0x68), SN74LVC1G126.",
        "5. Programming & Molecule Seat: 70x70 mm Base Molecule (MP1..MP4 GND), SWD on MC6..MC9, BOOT0 held low via R9 (10 kOhm).",
    ]
    sb.section_title("\n".join(note_lines), g(34), g(230), font_mm=1.905)

    # =========================================================================
    # VERIFY COMPLETENESS, SHORT-HOP RULE, BOUNDS, AND CONNECTIVITY
    # =========================================================================
    assert set(sb.placed_refs.keys()) == set(comp_map.keys()), (
        f"Missing/extra refs: missing={set(comp_map) - set(sb.placed_refs)}, "
        f"extra={set(sb.placed_refs) - set(comp_map)}"
    )
    assert len(sb.no_connects) == 23, f"Expected 23 no_connects, got {len(sb.no_connects)}"

    split_wires, junctions = sb.finalize_wires_and_junctions()

    # Check wires * 2 >= labels
    assert len(split_wires) * 2 >= len(sb.labels), (
        f"Too few wires ({len(split_wires)}) vs labels ({len(sb.labels)})"
    )

    # Check SHORT_HOP_MM = 25.4 mm on every label net with >= 2 labels
    by_label: dict[str, list[tuple[float, float]]] = defaultdict(list)
    for net, lx, ly, _ in sb.labels:
        by_label[net].append((lx, ly))
    for net, pts in by_label.items():
        if len(pts) >= 2:
            max_d = max(
                math.hypot(a[0] - b[0], a[1] - b[1]) for a in pts for b in pts
            )
            assert max_d > 25.4 + 5.0, f"SHORT_HOP violation on {net}: max_d={max_d:.2f} mm, pts={pts}"

    # Check union-find electrical connectivity matches design/netlist.json 100%!
    parent: dict[tuple[str, object], tuple[str, object]] = {}

    def find(a: tuple[str, object]) -> tuple[str, object]:
        while parent.setdefault(a, a) != a:
            parent[a] = parent[parent[a]]
            a = parent[a]
        return a

    def union(a: tuple[str, object], b: tuple[str, object]) -> None:
        ra, rb = find(a), find(b)
        if ra != rb:
            parent[ra] = rb

    for x1, y1, x2, y2 in split_wires:
        union(("pt", (x1, y1)), ("pt", (x2, y2)))
    for net, lx, ly, _ in sb.labels:
        union(("pt", (lx, ly)), ("net", net))
    for inst in sb.instances:
        ref = inst["ref"]
        if ref.startswith("#PWR"):
            for pxy in inst["pins"].values():
                union(("pt", pxy), ("net", inst["value"]))
        elif ref.startswith("#FLG"):
            continue
        else:
            for pnum, pxy in inst["pins"].items():
                union(("pt", pxy), ("pin", f"{ref}.{pnum}"))

    derived_nets: dict[str, set[str]] = defaultdict(set)
    net_root_names: dict[tuple[str, object], set[str]] = defaultdict(set)
    for k in list(parent.keys()):
        if k[0] == "net":
            net_root_names[find(k)].add(str(k[1]))
    for r, names in net_root_names.items():
        assert len(names) == 1, f"Shorted nets in schematic: {names}"

    for inst in sb.instances:
        ref = inst["ref"]
        if ref.startswith("#"):
            continue
        for pnum in inst["pins"]:
            pin_id = f"{ref}.{pnum}"
            r = find(("pin", pin_id))
            names = net_root_names.get(r, set())
            if names:
                derived_nets[next(iter(names))].add(pin_id)
            else:
                # Must be in no_connects!
                pxy = inst["pins"][pnum]
                assert pxy in sb.no_connects, f"Unconnected pin without no_connect or net label: {pin_id} at {pxy}"

    expected_nets = {k: set(v) for k, v in netlist["nets"].items()}
    assert set(derived_nets.keys()) == set(expected_nets.keys()), (
        f"Net set mismatch: missing={set(expected_nets) - set(derived_nets)}, "
        f"extra={set(derived_nets) - set(expected_nets)}"
    )
    for net_name, exp_pins in expected_nets.items():
        got_pins = derived_nets[net_name]
        assert got_pins == exp_pins, (
            f"Pin mismatch on {net_name}: missing={exp_pins - got_pins}, extra={got_pins - exp_pins}"
        )

    # Check free text bounding boxes do not overlap any symbol bbox or pin
    for txt, tx, ty, fsz in sb.texts:
        lines = txt.split("\n")
        max_len = max(len(line) for line in lines)
        tw = max_len * fsz * 0.85
        th = len(lines) * fsz * 1.65
        tb0, tb1, tb2, tb3 = tx - 1.0, ty - fsz, tx + tw + 1.0, ty + th
        assert tb0 >= 12.0 and tb1 >= 12.0 and tb2 <= 830.0 and tb3 <= 580.0, (
            f"Text outside A1 border: {(tb0, tb1, tb2, tb3)}"
        )
        for inst in sb.instances:
            if inst["ref"].startswith("#"):
                continue
            sx0, sy0, sx1, sy1 = inst["sheet_bbox"]
            overlap = not (tb2 < sx0 - 1.0 or tb0 > sx1 + 1.0 or tb3 < sy0 - 1.0 or tb1 > sy1 + 1.0)
            assert not overlap, f"Text '{lines[0][:30]}' overlaps {inst['ref']} bbox {(sx0, sy0, sx1, sy1)}"

    # =========================================================================
    # SERIALIZE kicad/microgoose-spine.kicad_sch
    # =========================================================================
    used_lib_ids: list[str] = []
    for inst in sb.instances:
        if inst["lib_id"] not in used_lib_ids:
            used_lib_ids.append(inst["lib_id"])

    out: list[str] = []
    out.append(
        '(kicad_sch\n'
        '  (version 20250114)\n'
        '  (generator "eeschema")\n'
        '  (generator_version "10.0")\n'
        f'  (uuid "{root_uuid}")\n'
        '  (paper "A1")\n'
        '  (title_block\n'
        '    (title "Microgoose Spine: Power, Torso IMU & 1 Mbps Actuator Controller")\n'
        '    (date "2026-11-11")\n'
        '    (rev "A")\n'
        '    (company "Adom")\n'
        '    (comment 1 "70x70 mm Base Molecule | 2S Li-ion to 5V 4A Buck + 3.3V LDO | STM32G431CB")\n'
        '    (comment 2 "wiki.adom.inc/drew2/microgoose")\n'
        '  )\n'
        '  (lib_symbols'
    )
    for lid in used_lib_ids:
        indented = "\n".join("    " + ln for ln in embedded_blocks[lid].splitlines())
        out.append(indented)
    out.append("  )")

    # Junctions
    for idx, (jx, jy) in enumerate(junctions):
        out.append(
            f'  (junction (at {fmt(jx)} {fmt(jy)}) (diameter 0) (color 0 0 0 0)\n'
            f'    (uuid "{det_uuid(f"junc-{idx}-{jx}-{jy}")}")\n'
            f'  )'
        )

    # No-connects
    for idx, (nx, ny) in enumerate(sb.no_connects):
        out.append(
            f'  (no_connect (at {fmt(nx)} {fmt(ny)})\n'
            f'    (uuid "{det_uuid(f"nc-{idx}-{nx}-{ny}")}")\n'
            f'  )'
        )

    # Wires
    for idx, (x1, y1, x2, y2) in enumerate(split_wires):
        out.append(
            f'  (wire (pts (xy {fmt(x1)} {fmt(y1)}) (xy {fmt(x2)} {fmt(y2)}))\n'
            f'    (stroke (width 0) (type default))\n'
            f'    (uuid "{det_uuid(f"wire-{idx}-{x1}-{y1}-{x2}-{y2}")}")\n'
            f'  )'
        )

    # Local net labels
    for idx, (net, lx, ly, lrot) in enumerate(sb.labels):
        just = "right bottom" if lrot == 180 else "left bottom"
        out.append(
            f'  (label "{net}" (at {fmt(lx)} {fmt(ly)} {lrot}) (fields_autoplaced yes)\n'
            f'    (effects (font (size 1.27 1.27)) (justify {just}))\n'
            f'    (uuid "{det_uuid(f"lbl-{idx}-{net}-{lx}-{ly}")}")\n'
            f'  )'
        )

    # Section headings and design calculation note
    for idx, (txt, tx, ty, fsz) in enumerate(sb.texts):
        escaped = txt.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
        out.append(
            f'  (text "{escaped}" (exclude_from_sim no)\n'
            f'    (at {fmt(tx)} {fmt(ty)} 0)\n'
            f'    (effects (font (size {fmt(fsz)} {fmt(fsz)}) bold) (justify left top))\n'
            f'    (uuid "{det_uuid(f"txt-{idx}")}")\n'
            f'  )'
        )

    # Placed symbols
    for inst in sb.instances:
        ref = inst["ref"]
        iuuid = det_uuid(f"sym-{ref}")
        rx, ry = inst["ref_xy"]
        vx, vy = inst["val_xy"]
        hide_ref = " (hide yes)" if inst.get("hide_ref") else ""
        props = [
            f'    (property "Reference" "{ref}" (at {fmt(rx)} {fmt(ry)} 0)\n'
            f'      (effects (font (size 1.27 1.27)){hide_ref})\n'
            f'    )',
            f'    (property "Value" "{inst["value"]}" (at {fmt(vx)} {fmt(vy)} 0)\n'
            f'      (effects (font (size 1.27 1.27)))\n'
            f'    )',
            f'    (property "Footprint" "{inst["fp"]}" (at {fmt(inst["cx"])} {fmt(inst["cy"])} 0)\n'
            f'      (effects (font (size 1.27 1.27)) (hide yes))\n'
            f'    )',
            f'    (property "Datasheet" "" (at {fmt(inst["cx"])} {fmt(inst["cy"])} 0)\n'
            f'      (effects (font (size 1.27 1.27)) (hide yes))\n'
            f'    )',
        ]
        if inst["mpn"]:
            props.append(
                f'    (property "MPN" "{inst["mpn"]}" (at {fmt(inst["cx"])} {fmt(inst["cy"])} 0)\n'
                f'      (effects (font (size 1.27 1.27)) (hide yes))\n'
                f'    )'
            )
        if inst["mfr"]:
            props.append(
                f'    (property "Manufacturer" "{inst["mfr"]}" (at {fmt(inst["cx"])} {fmt(inst["cy"])} 0)\n'
                f'      (effects (font (size 1.27 1.27)) (hide yes))\n'
                f'    )'
            )
        pin_lines = "\n".join(
            f'    (pin "{pnum}" (uuid "{det_uuid(f"pin-{ref}-{pnum}")}"))'
            for pnum in inst["pins"]
        )
        out.append(
            f'  (symbol\n'
            f'    (lib_id "{inst["lib_id"]}")\n'
            f'    (at {fmt(inst["cx"])} {fmt(inst["cy"])} {inst["rot"]})\n'
            f'    (unit 1)\n'
            f'    (exclude_from_sim no)\n'
            f'    (in_bom {inst["in_bom"]})\n'
            f'    (on_board {inst["on_board"]})\n'
            f'    (dnp no)\n'
            f'    (fields_autoplaced yes)\n'
            f'    (uuid "{iuuid}")\n'
            + "\n".join(props)
            + "\n"
            + pin_lines
            + "\n"
            f'    (instances\n'
            f'      (project "microgoose-spine"\n'
            f'        (path "/{root_uuid}"\n'
            f'          (reference "{ref}")\n'
            f'          (unit 1)\n'
            f'        )\n'
            f'      )\n'
            f'    )\n'
            f'  )'
        )

    out.append('  (sheet_instances\n    (path "/"\n      (page "1")\n    )\n  )')
    out.append("  (embedded_fonts no)\n)\n")

    sch_path = KICAD_DIR / "microgoose-spine.kicad_sch"
    sch_path.write_text("\n".join(out))
    print(
        f"OK: wrote {sch_path} ({len(sb.placed_refs)} components, "
        f"{len(split_wires)} wires, {len(sb.labels)} labels, {len(junctions)} junctions, "
        f"{len(sb.no_connects)} no_connects)"
    )


if __name__ == "__main__":
    build_all()