main
John Lauer Family contract: pipeline 1.0.0 that built the three VL53Lx pages 8e4500f
#!/usr/bin/env python3
"""Merge symbols/<MPN>/<MPN>.kicad_sym into libraries/Adom_ToF.kicad_sym, keeping the sourcing
properties (MPN, Manufacturer, Mouser, DigiKey) the library already carries for each part."""
import os, re, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PARTS = ["VL53L5CX", "VL53L7CX", "VL53L8CX"]
KEEP = ("MPN", "Manufacturer", "Mouser", "DigiKey")

def block(text, head):
    i = text.index(head); depth = 0; j = i
    while True:
        c = text[j]
        if c == "(": depth += 1
        elif c == ")":
            depth -= 1
            if depth == 0: return i, j + 1
        j += 1

def prop_lines(blk, names):
    out = []
    for m in re.finditer(r'\n(\s*\(property "([^"]+)" [^\n]*(?:\n(?!\s*\(property)[^\n]*)*)', blk):
        if m.group(2) in names: out.append(m.group(1))
    return out

lib_path = os.path.join(ROOT, "libraries", "Adom_ToF.kicad_sym")
lib = open(lib_path).read()
for m in PARTS:
    new = open(os.path.join(ROOT, "symbols", m, f"{m}.kicad_sym")).read()
    ni, nj = block(new, f'(symbol "{m}"'); nb = new[ni:nj]
    oi, oj = block(lib, f'(symbol "{m}"'); ob = lib[oi:oj]
    have = set(re.findall(r'\(property "([^"]+)"', nb))
    extra = [p for p in prop_lines(ob, KEEP) if re.search(r'\(property "([^"]+)"', p).group(1) not in have]
    if extra:
        # insert after the last property of the new block
        last = list(re.finditer(r'\n\s*\(property "[^"]+" [^\n]*(?:\n(?!\s*\(property)(?!\s*\(symbol)[^\n]*)*', nb))[-1]
        nb = nb[:last.end()] + "\n" + "\n".join(extra) + nb[last.end():]
    lib = lib[:oi] + nb + lib[oj:]
    print(f"{m}: merged, kept {len(extra)} sourcing properties, outline {re.search(r'Adom_Chip_Outline\" \"([^\"]*)', nb).group(1) if 'Adom_Chip_Outline' in nb else '?'}")
open(lib_path, "w").write(lib)
print("wrote", lib_path)