main
John Lauer Family contract: pipeline 1.0.0 that built the three VL53Lx pages 8e4500f
#!/usr/bin/env python3
"""Assemble the three wiki component pages (adom/vl53l5cx, vl53l7cx, vl53l8cx) into wiki/<slug>/.

Reads tools/parts_data.json (specs + pins with datasheet page citations, sourcing snapshot) and
gathers every artifact this project produced: symbol, footprint, .lbr, the manufacturer STEP
(untouched) and its Z-up derivatives (plain / FoV / etched / FoV+etched / hero), GLBs, renders,
chip-outline artwork cache, datasheet, provenance JSON. Writes page.json, package.json, README.md,
LICENSE. Nothing here talks to the wiki; publish with tools/publish_wiki_pages.sh.
"""
import os, sys, json, re, shutil, hashlib, glob, datetime

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA = json.load(open(os.path.join(ROOT, "tools", "parts_data.json")))
LIB = os.environ.get("CHIP_FETCHER_LIBRARY", os.path.expanduser("~/project/chip-fetcher/library"))
TODAY = datetime.date.today().isoformat()


def sha(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for c in iter(lambda: f.read(1 << 20), b""):
            h.update(c)
    return h.hexdigest()


def sexpr_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 text[i:j + 1]
        j += 1


def single_symbol_lib(mpn):
    lib = open(os.path.join(ROOT, "libraries", "Adom_ToF.kicad_sym")).read()
    blk = sexpr_block(lib, f'(symbol "{mpn}"')
    head = lib[:lib.index("(symbol ")]
    return head.rstrip() + "\n  " + blk.replace("\n", "\n  ") + "\n)\n"


def copy(src, dst):
    os.makedirs(os.path.dirname(dst), exist_ok=True)
    shutil.copyfile(src, dst); return dst


def build(mpn):
    d = DATA[mpn]; slug = d["slug"]; out = os.path.join(ROOT, "wiki", slug)
    if os.path.isdir(out): shutil.rmtree(out)
    os.makedirs(out)
    files = {}
    def add(rel, src):
        if src and os.path.exists(src):
            copy(src, os.path.join(out, rel)); files[rel] = src
        else:
            print(f"  MISSING {rel} <- {src}")
    der = os.path.join(ROOT, "3d-chips", "derived")
    open(os.path.join(out, f"{slug}.kicad_sym"), "w").write(single_symbol_lib(mpn)); files[f"{slug}.kicad_sym"] = "generated"
    add(f"{slug}.kicad_mod", os.path.join(ROOT, "footprints", f"{mpn}.kicad_mod"))
    add(f"{slug}.lbr", os.path.join(ROOT, "libraries", "fusion", f"{mpn}.lbr"))
    for v, rel in (("", f"{slug}.step"), ("-fov", f"{slug}-fov.step"), ("-etched", f"{slug}-etched.step"), ("-fov-etched", f"{slug}-fov-etched.step"), ("-hero", f"{slug}-hero.step")):
        add(rel, os.path.join(der, f"{mpn}{v}.step"))
        if v != "-hero":
            add(f"provenance/{slug}{v}.step.json", os.path.join(der, f"{mpn}{v}.provenance.json"))
    add(f"provenance/{slug}-hero.json", os.path.join(der, f"{mpn}-hero.provenance.json"))
    for v in ("", "-fov", "-etched", "-fov-etched", "-hero"):
        add(f"{slug}{v}.glb", os.path.join(der, f"{mpn}{v}.glb"))
    add(f"vendor/{mpn}-cse-original.step", os.path.join(ROOT, "3d-chips", "vendor", f"{mpn}-cse-yup.step"))
    add(f"{slug}-adom-datasheet-model.step", os.path.join(ROOT, "3d-chips", f"{mpn}.step"))
    add(f"docs/{slug}-datasheet.pdf", os.path.join(ROOT, "datasheets", f"{slug}.pdf"))
    for r in ("etched-iso", "fov-etched-iso", "hero-iso"):
        add(f"renders/{slug}-{r}.png", os.path.join(ROOT, "renders", f"{mpn}-{r}.png"))
    add("docs/hero.png", os.path.join(ROOT, "renders", f"{mpn}-hero-iso.png"))
    # embedded viewers
    os.makedirs(os.path.join(out, "viewers"), exist_ok=True)
    for kind, tool, src in (("symbol", "adom-symbol", os.path.join(out, f"{slug}.kicad_sym")), ("footprint", "adom-footprint", os.path.join(out, f"{slug}.kicad_mod"))):
        dst = os.path.join(out, "viewers", f"{kind}.html")
        rc = os.system(f"timeout 180 {tool} embed --file {src} --out {dst} >/dev/null 2>&1")
        if rc == 0 and os.path.exists(dst): files[f"viewers/{kind}.html"] = tool
        else: print(f"  viewer {kind} failed")
    # artwork cache from chip-fetcher (outline SVGs + iso PNG + manifest)
    art = os.path.join(LIB, mpn)
    for f in sorted(glob.glob(os.path.join(art, f"{mpn}-3d-outline-*.svg"))):
        if "-named" in f: continue                      # name-on-top variants are wrong for optical tops
        add(f"artwork/{os.path.basename(f)}", f)
    for f in (f"{mpn}-3d-iso.png", f"{mpn}-3d-iso-icon.png", f"{mpn}-thumbs.json"):
        add(f"artwork/{f}", os.path.join(art, f))
    # datasheet page crops: the cited pages as images (provenance evidence)
    figs = []
    for label, page in d.get("figures", []):
        rel = f"docs/figures/{slug}-ds-p{page}.png"; dst = os.path.join(out, rel)
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        os.system(f"pdftoppm -f {page} -l {page} -r 70 -png {os.path.join(ROOT, 'datasheets', slug + '.pdf')} {dst[:-4]} >/dev/null 2>&1")
        cand = [f for f in glob.glob(dst[:-4] + "*.png")]
        if cand:
            os.replace(cand[0], dst); files[rel] = "pdftoppm"; figs.append((label, page, rel))
    d["_figs"] = figs
    # footprint verification report
    add("provenance/footprint-vs-samacsys.json", os.path.join(ROOT, "provenance", f"{mpn}-footprint-vs-samacsys.json"))

    hashes = {rel: sha(os.path.join(out, rel)) for rel in files if os.path.exists(os.path.join(out, rel))}
    vendor_sha = hashes.get(f"vendor/{mpn}-cse-original.step", "")
    types = {p["number"]: p["type"] for p in json.load(open(os.path.join(ROOT, "symbols", mpn, f"{mpn}-create.json")))["pins"]}
    pins = [dict(p, type=types.get(p["n"], p.get("type", "passive"))) for p in d["pins"]]
    comp = {
        "mpn": d["order_code"], "manufacturer": "STMicroelectronics", "package": d["package"],
        "pin_count": len(pins), "category": "Sensors", "subcategory": "Time-of-Flight multizone ranging sensor",
        "datasheet": d["datasheet_url"], "product_page": d["product_url"],
        "body_size": d["body_size"],
        "parts": {"symbol": f"{slug}.kicad_sym", "footprint": f"{slug}.kicad_mod", "model_3d": f"{slug}-hero.glb",
                  "model_3d_plain": f"{slug}-etched.glb", "model_3d_step": f"{slug}-etched.step", "model_3d_step_plain": f"{slug}.step",
                  "step": f"{slug}-etched.step", "lbr": f"{slug}.lbr", "datasheet": f"docs/{slug}-datasheet.pdf"},
        "manufacturer_links": [{"label": a, "url": b, "note": c} for a, b, c in d.get("manufacturer_links", [])],
        "source": {"authority": "STMicroelectronics", "product_page": d["product_url"], "datasheet": d["datasheet_url"], "cad": "st.com CAD Resources tab (SamacSys / Component Search Engine partID " + str(d["cse_part_id"]) + ")"},
        "distributor_links": {
            "mouser": {"part": next(r["sku"] for r in d["sourcing"]["rows"] if r["dist"] == "Mouser"), "url": d["distributor_links"]["mouser"]},
            "digikey": {"part": next(r["sku"] for r in d["sourcing"]["rows"] if r["dist"] == "DigiKey"), "url": d["distributor_links"]["digikey"]},
            "lcsc": False,
        },
        "pins": [{"number": p["n"], "name": p["name"], "type": p["type"], "description": p["desc"], "datasheet_page": d["pin_table_pages"]} for p in pins],
        "models_3d": [
            {"file": f"vendor/{mpn}-cse-original.step", "role": "manufacturer original (SamacSys via st.com CAD tab), bytes untouched", "up_axis": "Y", "sha256": vendor_sha},
            {"file": f"{slug}.step", "role": "manufacturer body, Adom Z-up, seated on z=0, FoV cones removed", "up_axis": "Z"},
            {"file": f"{slug}-fov.step", "role": "same + the manufacturer's field-of-view cones kept as separate solids (toggle them in your viewer)", "up_axis": "Z"},
            {"file": f"{slug}-etched.step", "role": "library model: Z-up + virtual MPN inlay on the +Y side wall (top carries the optics, never mark it)", "up_axis": "Z"},
            {"file": f"{slug}-fov-etched.step", "role": "FoV cones + side etch", "up_axis": "Z"},
            {"file": f"{slug}-hero.glb", "role": "page hero only: etched chip + teal dashed pad outlines (50 %), silkscreen (30 %), pad signal labels (50 %). Not for boards.", "up_axis": "Z"},
            {"file": f"{slug}-adom-datasheet-model.step", "role": "Adom-authored model built from the datasheet outline drawing (coloured, used before the manufacturer STEP was fetched)", "up_axis": "Z"},
        ],
        "provenance": {
            "datasheet": {"id": d["ds_id"], "url": d["datasheet_url"], "pages": d["ds_pages"], "sha256": hashes.get(f"docs/{slug}-datasheet.pdf", "")[:16], "source_tier": "mfr"},
            "pins": {"total": len(pins), "described": len(pins), "cites_pages": True, "source": f"{d['ds_id']} Table 3, page(s) {d['pin_table_pages']}"},
            "footprint": {"source": f"{d['ds_id']} recommended solder pattern, page {d['solder_page']}", "verified_against": "SamacSys/CSE land pattern (pad-by-pad, see provenance/footprint-vs-samacsys.json)"},
            "model_3d": {"source": "st.com CAD Resources tab (SamacSys widget), st.componentsearchengine.com partID " + str(d["cse_part_id"]), "sha256": vendor_sha, "transform": "see provenance/*.step.json"},
            "symbol": {"tool": "adom-symbol 1.2.0", "chip_outline": "chip-thumbnailer 0.6.0 outline of the side-etched Z-up model (un-named variant)"},
            "tools": ["adom-symbol 1.2.0", "adom-chip-thumbnailer 0.6.0", "service-step2glb 1.3.12", "tof-8x8-sensors/tools (vendor_step.py, hero_step.py, glb_alpha.py, build_parts.py)"],
            "sourcing_snapshot": d["sourcing"]["date"],
        },
        "viewers": {"symbol": "viewers/symbol.html", "footprint": "viewers/footprint.html"},
        "artwork_cache": f"artwork/{mpn}-thumbs.json",
    }
    page = {
        "schema_version": 1, "type": "component", "slug": slug, "title": mpn,
        "brief": d["brief"], "version": "0.1.0", "license": "CC-BY-4.0",
        "tags": ["component", "sensor", "time-of-flight", "tof", "multizone", "8x8", "lga-16", "stmicroelectronics", "flightsense", "i2c"] + d.get("extra_tags", []),
        "component": comp,
        "metadata": {"specs": {k: v for k, v, _ in d["specs"]}},
        "sections": ["hero", "viewers", "readme", "breadcrumbs", "info"],
        "discovery_triggers": d["triggers"],
        "discovery_pitch": d["pitch"],
        "author": {"name": "John Lauer", "email": "[email protected]"},
        "dependencies": {},
        "hero": {"type": "image", "path": "docs/hero.png", "chrome": False},
        "files": sorted(files.keys()) + ["page.json", "README.md", "LICENSE"],
        "visibility": {"public": True},
        "variants": [{"mpn": d["order_code"], "kind": "packaging", "note": "tape and reel, 3600 pcs minimum order (datasheet order-code table)"}],
        "related": d["related"],
    }
    json.dump(page, open(os.path.join(out, "page.json"), "w"), indent=2)
    json.dump({"slug": slug, "version": "0.1.0", "type": "component", "description": d["brief"], "tags": page["tags"],
               "dependencies": {}, "hero": page["hero"], "files": page["files"]}, open(os.path.join(out, "package.json"), "w"), indent=2)
    open(os.path.join(out, "README.md"), "w").write(readme(mpn, dict(d, pins=pins, _figs=figs), hashes))
    open(os.path.join(out, "LICENSE"), "w").write(LICENSE.format(year=TODAY[:4]))
    json.dump(hashes, open(os.path.join(out, "provenance", "file-hashes.json"), "w"), indent=1)
    print(f"{slug}: {len(files)} files, {sum(os.path.getsize(os.path.join(out, r)) for r in files if os.path.exists(os.path.join(out, r))) / 1e6:.1f} MB")


def readme(mpn, d, hashes):
    slug = d["slug"]; ds = d["ds_id"]
    L = [f"# {mpn}", "", f"**STMicroelectronics** · Time-of-Flight 8x8 multizone ranging sensor · {d['package']}", "",
         d["overview"], "",
         f"Order code **{d['order_code']}** (tape and reel, 3600 pcs minimum, {ds} page {d['order_page']}). "
         f"Datasheet: [{ds}]({d['datasheet_url']}) (local copy: `docs/{slug}-datasheet.pdf`). Product page: [st.com]({d['product_url']}).", "",
         "## Manufacturer and resources", "",
         "Everything on this page traces back to STMicroelectronics. Start here for the original documents, software and CAD.", "",
         "| Resource | Link | Why you need it |", "|---|---|---|"]
    for label, url, why in d.get("manufacturer_links", []):
        L.append(f"| {label} | [open]({url}) | {why} |")
    L += ["", "Evaluation-kit and software part numbers are ST's names as listed with this product; the links are st.com searches so they stay valid when ST moves a document. Kept locally: the datasheet in `docs/`, the manufacturer 3D model in `vendor/` (untouched bytes, sha256 in `provenance/file-hashes.json`).", "",
         "## Pinout", "", f"Source: {ds} Table 3, page {d['pin_table_pages']}. Pad A1 is bottom-right in the top view (outline drawing); the footprint marks it with the chamfered corner and dot.", "",
         "| Pad | Name | Type | Function |", "|---|---|---|---|"]
    for p in d["pins"]:
        L.append(f"| {p['n']} | {p['name']} | {p['type']} | {p['desc']} |")
    L += ["", "## Key specifications", "", "| Parameter | Value | Source |", "|---|---|---|"]
    for k, v, src in d["specs"]:
        L.append(f"| {k} | {v} | {ds} {src} |")
    L += ["", "## Sourcing", "", f"Snapshot {d['sourcing']['date']} (single-unit price, stock at that moment; re-check before ordering).", "",
          "| Distributor | Part | Price @1 | Stock | Link |", "|---|---|---|---|---|"]
    for row in d["sourcing"]["rows"]:
        L.append(f"| {row['dist']} | {row['sku']} | {row['price']} | {row['stock']} | [open]({row['url']}) |")
    L += ["", "## Packaging, handling and marking", "",
          f"- Tape and reel, EIA-481 carrier tape; orientation and pocket drawing on {ds} page {d['tape_pages']}.",
          f"- Moisture sensitivity level 3 (IPC/JEDEC J-STD-020), {ds} page {d['msl_page']}. Handle with non-marring ESD-safe tweezers; never touch the optical windows.",
          f"- Device marking and the marking area on the cap: {ds} page {d['marking_pages']}.",
          f"- Recommended solder pattern (the footprint here follows it pad for pad): {ds} page {d['solder_page']}.",
          f"- Reflow and cover-glass guidance: {d['app_notes']}.", "",
          "## CAD", "",
          "Everything below is Adom-authored from the datasheet and the manufacturer CAD, licensed CC-BY-4.0; the manufacturer's own files keep ST's and SamacSys's terms.", "",
          "| File | What it is |", "|---|---|",
          f"| `{slug}.kicad_sym` | KiCad symbol, two-column layout with intelligent pin groups (Power, Ground, I2C, Control, Reserved) and the chip outline of this exact part baked in the body (adom-symbol 1.2.0). The MPN in the outline is on the side wall, the top face carries the emitter and receiver windows. |",
          f"| `{slug}.kicad_mod` | KiCad footprint from the datasheet solder pattern (2 x 7 pads on 0.75 mm pitch, two side pads, thermal pad). Verified pad-by-pad against the SamacSys land pattern: `provenance/footprint-vs-samacsys.json`. |",
          f"| `{slug}.lbr` | Fusion 360 / EAGLE library (symbol + package + device). |",
          f"| `{slug}-etched.step` / `.glb` | **Library model.** Manufacturer body, Adom Z-up, seated on z = 0, field-of-view cones removed, virtual MPN inlay on the +Y side wall. |",
          f"| `{slug}.step` / `.glb` | Same body, no marking. |",
          f"| `{slug}-fov.step` / `.glb`, `{slug}-fov-etched.step` / `.glb` | The manufacturer's field-of-view cones kept as separate solids so you can switch them on when you want to see the coverage and off when you place the part. |",
          f"| `{slug}-hero.glb` | Page hero: the etched chip plus teal dashed copper-pad outlines (50 % opacity), silkscreen (30 %) and pad signal labels (50 %). Reference artwork only, never put it on a board. |",
          f"| `vendor/{mpn}-cse-original.step` | Manufacturer STEP exactly as downloaded from the st.com CAD Resources tab (SamacSys), Y-up, sha256 `{hashes.get(f'vendor/{mpn}-cse-original.step','')[:16]}`. |",
          f"| `{slug}-adom-datasheet-model.step` | Adom-authored coloured model built from the datasheet outline drawing (CadQuery), used before the manufacturer STEP was fetched. |",
          f"| `artwork/` | chip-thumbnailer outline cache (11 styles) and shaded iso render of the etched model; `{mpn}-thumbs.json` is the manifest. |",
          "", "The 3D transforms (Y-up to Z-up rotation, yaw, seating translation, which solids were dropped, etch placement) are recorded per file in `provenance/*.step.json`.", "",
          "## Provenance", "", "| Data | Source | Reference | Evidence |", "|---|---|---|---|",
          f"| Identity, features | {ds} | page 1 | datasheet copy in `docs/` |",
          f"| Pin functions | {ds} Table 3 | page {d['pin_table_pages']} | table above quotes the datasheet |",
          f"| Package size | {ds} outline drawing | page {d['outline_pages']} | body bbox measured on the manufacturer STEP in `provenance/{slug}.step.json` |",
          f"| Land pattern | {ds} recommended solder pattern | page {d['solder_page']} | `provenance/footprint-vs-samacsys.json` |",
          f"| 3D model | st.com CAD Resources tab (SamacSys), CSE partID {d['cse_part_id']} | fetched {d['fetched']} | sha256 in page.json and `provenance/file-hashes.json` |",
          f"| Price and stock | {', '.join(sorted(set(r['dist'] for r in d['sourcing']['rows'])))} | {d['sourcing']['date']} | links above |",]
    if d.get("_figs"):
        L += ["", "### Cited datasheet pages", "", f"Page images rendered from the {ds} copy in `docs/` (click to enlarge).", ""]
        L += ["| Page | What it shows |", "|---|---|"]
        for label, page, rel in d["_figs"]:
            L.append(f"| [page {page}]({rel}) | {label} |")
    if d.get("legacy_figures"):
        L += ["", "### Datasheet figure crops", "", f"Figure crops from {ds} that an earlier revision of this page extracted (kept at the repo root):", ""]
        for f in d["legacy_figures"]:
            L.append(f"- [{f}]({f})")
    L += ["", "## Related", ""]
    for r in d["related"]:
        L.append(f"- [{r['title']}]({r['url']}) - {r['note']}")
    L += ["", "## Chip outline cache", "", f"::adom-chip-thumbnail{{src=\"/adom/{slug}/render/artwork/{mpn}-thumbs.json\" mpn=\"{mpn}\" package=\"{d['package']}\"}}", ""]
    return "\n".join(L)


LICENSE = """Adom-authored content of this component page (symbol, footprint, Fusion library, derived and
annotated 3D models, renders, README, page metadata) is licensed under the Creative Commons
Attribution 4.0 International License (CC-BY-4.0), https://creativecommons.org/licenses/by/4.0/.
Copyright {year} Adom Inc.

Third-party material keeps its own terms and attribution: the datasheet in docs/ is
STMicroelectronics' document; the file under vendor/ is the manufacturer 3D model as served by
STMicroelectronics' CAD Resources tab (SamacSys / Component Search Engine). Derived models retain
that attribution and record their source hash and transform in provenance/.
"""

if __name__ == "__main__":
    for m in (sys.argv[1:] or ["VL53L5CX", "VL53L7CX", "VL53L8CX"]):
        build(m)