main
Drew Owens Scrub internal hostnames, quota ledger, local paths, and private links for public release 09af481
#!/usr/bin/env python3
"""Audit of the 2 KiCad STEP export geometry warnings near C2, C3, and MC2.

Inspects:
1. kicad/microgoose-spine.export.json (exact diagnostic bounding boxes and z=1.51 mm plane)
2. kicad/microgoose-spine.kicad_pcb (exact footprints, pads, tracks, vias, and filled_polygon
   vertices on F.Cu / B.Cu in the warning neighborhood)
3. aiflow/run/manufacturing/export-check.json & drc-saved-fills.json (DRC & Gerber parity)
4. kicad/microgoose-spine.step (ISO-10303-21 entity & component occurrence completeness)

Outputs:
- validation/step_geometry_audit.json
- docs/analysis/step_c2_c3_mc2_audit.png
"""

from __future__ import annotations

import json
import math
import re
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon as MplPolygon, Rectangle, Circle
import numpy as np

ROOT = Path(__file__).resolve().parents[1]
PCB_PATH = ROOT / "kicad" / "microgoose-spine.kicad_pcb"
EXPORT_JSON_PATH = ROOT / "kicad" / "microgoose-spine.export.json"
STEP_PATH = ROOT / "kicad" / "microgoose-spine.step"
EXPORT_CHECK_PATH = ROOT / "aiflow" / "run" / "manufacturing" / "export-check.json"
DRC_PATH = ROOT / "aiflow" / "run" / "manufacturing" / "drc-saved-fills.json"
FIELDS_PATH = ROOT / "aiflow" / "run" / "fields" / "fields.json"

OUT_JSON = ROOT / "validation" / "step_geometry_audit.json"
OUT_PNG = ROOT / "docs" / "analysis" / "step_c2_c3_mc2_audit.png"


def extract_balanced_blocks(text: str, head: str) -> list[str]:
    blocks = []
    idx = 0
    needle = f"({head}"
    n = len(text)
    while True:
        pos = text.find(needle, idx)
        if pos == -1:
            break
        after = pos + len(needle)
        if after < n and text[after] not in (" ", "\n", "\t", "\r", ")"):
            idx = after
            continue
        depth = 0
        end = pos
        in_str = False
        while end < n:
            ch = text[end]
            if ch == '"' and (end == 0 or text[end - 1] != "\\"):
                in_str = not in_str
            elif not in_str:
                if ch == "(":
                    depth += 1
                elif ch == ")":
                    depth -= 1
                    if depth == 0:
                        end += 1
                        break
            end += 1
        blocks.append(text[pos:end])
        idx = end
    return blocks


def parse_pcb_region(pcb_text: str, roi: tuple[float, float, float, float]) -> dict:
    x_min, x_max, y_min, y_max = roi

    # Parse footprints in ROI
    footprints = []
    for fp_blk in extract_balanced_blocks(pcb_text, "footprint"):
        m_at = re.search(r"\(at\s+([-\d.]+)\s+([-\d.]+)(?:\s+([-\d.]+))?\)", fp_blk)
        if not m_at:
            continue
        fx = float(m_at.group(1))
        fy = float(m_at.group(2))
        frot = float(m_at.group(3) or 0.0)
        m_ref = re.search(r'\(property\s+"Reference"\s+"([^"]+)"', fp_blk)
        if not m_ref:
            m_ref = re.search(r'\(fp_text\s+reference\s+"?([^"\s)]+)"?', fp_blk)
        ref = m_ref.group(1) if m_ref else "?"
        if not (x_min - 3.0 <= fx <= x_max + 3.0 and y_min - 3.0 <= fy <= y_max + 3.0):
            continue
        m_val = re.search(r'\(property\s+"Value"\s+"([^"]+)"', fp_blk)
        val = m_val.group(1) if m_val else ""

        pads = []
        rad = math.radians(frot)
        c_r, s_r = math.cos(rad), math.sin(rad)
        for pad_blk in extract_balanced_blocks(fp_blk, "pad"):
            m_pad = re.match(r'\(pad\s+"?([^"\s)]+)"?\s+(\S+)\s+(\S+)', pad_blk)
            m_pat = re.search(r"\(at\s+([-\d.]+)\s+([-\d.]+)(?:\s+([-\d.]+))?\)", pad_blk)
            m_psz = re.search(r"\(size\s+([-\d.]+)\s+([-\d.]+)\)", pad_blk)
            m_net = re.search(r'\(net\s+(?:\d+\s+)?"([^"]+)"\)', pad_blk)
            if m_pad and m_pat and m_psz:
                px_rel = float(m_pat.group(1))
                py_rel = float(m_pat.group(2))
                # KiCad footprint local -> board transform (y-down, positive angle CCW in KiCad)
                bx = fx + px_rel * c_r + py_rel * s_r
                by = fy - px_rel * s_r + py_rel * c_r
                pw = float(m_psz.group(1))
                ph = float(m_psz.group(2))
                if abs(round(frot) % 180) == 90:
                    pw, ph = ph, pw
                pads.append({
                    "pad": m_pad.group(1),
                    "kind": m_pad.group(2),
                    "shape": m_pad.group(3),
                    "x": round(bx, 4),
                    "y": round(by, 4),
                    "w": round(pw, 4),
                    "h": round(ph, 4),
                    "net": m_net.group(1) if m_net else "",
                })
        footprints.append({
            "ref": ref,
            "value": val,
            "x": fx,
            "y": fy,
            "rot_deg": frot,
            "pads": pads,
        })

    # Parse segments in ROI
    segments = []
    for seg_blk in extract_balanced_blocks(pcb_text, "segment"):
        ms = re.search(
            r"\(start\s+([-\d.]+)\s+([-\d.]+)\).*?\(end\s+([-\d.]+)\s+([-\d.]+)\)"
            r".*?\(width\s+([-\d.]+)\).*?\(layer\s+\"([^\"]+)\"\).*?\(net\s+(\d+)\)",
            seg_blk,
            re.S,
        )
        if not ms:
            continue
        x1, y1, x2, y2, w = map(float, ms.groups()[:5])
        layer = ms.group(6)
        net_id = int(ms.group(7))
        if max(x1, x2) >= x_min and min(x1, x2) <= x_max and max(y1, y2) >= y_min and min(y1, y2) <= y_max:
            segments.append({"x1": x1, "y1": y1, "x2": x2, "y2": y2, "w": w, "layer": layer, "net_id": net_id})

    # Parse vias in ROI
    vias = []
    for via_blk in extract_balanced_blocks(pcb_text, "via"):
        mv = re.search(r"\(at\s+([-\d.]+)\s+([-\d.]+)\).*?\(size\s+([-\d.]+)\).*?\(drill\s+([-\d.]+)\)", via_blk, re.S)
        if mv:
            vx, vy, vsz, vdr = map(float, mv.groups())
            if x_min <= vx <= x_max and y_min <= vy <= y_max:
                vias.append({"x": vx, "y": vy, "size": vsz, "drill": vdr})

    # Parse filled_polygon blocks inside zones
    filled_polys = []
    for z_blk in extract_balanced_blocks(pcb_text, "zone"):
        m_znet = re.search(r'\((?:net_name|net)\s+"([^"]+)"\)', z_blk)
        znet = m_znet.group(1) if m_znet else "?"
        m_zname = re.search(r'\(name\s+"([^"]+)"\)', z_blk)
        zname = m_zname.group(1) if m_zname else znet
        for fp_poly in extract_balanced_blocks(z_blk, "filled_polygon"):
            m_lay = re.search(r'\(layer\s+"([^"]+)"\)', fp_poly)
            lay = m_lay.group(1) if m_lay else "?"
            pts = [(float(a), float(b)) for a, b in re.findall(r"\(xy\s+([-\d.]+)\s+([-\d.]+)\)", fp_poly)]
            if not pts:
                continue
            xs = [p[0] for p in pts]
            ys = [p[1] for p in pts]
            if max(xs) >= x_min and min(xs) <= x_max and max(ys) >= y_min and min(ys) <= y_max:
                filled_polys.append({
                    "zone_name": zname,
                    "net": znet,
                    "layer": lay,
                    "pts": pts,
                })

    return {
        "footprints": footprints,
        "segments": segments,
        "vias": vias,
        "filled_polys": filled_polys,
    }


def point_to_seg_dist(px: float, py: float, x1: float, y1: float, x2: float, y2: float) -> float:
    dx, dy = x2 - x1, y2 - y1
    l2 = dx * dx + dy * dy
    if l2 <= 1e-18:
        return math.hypot(px - x1, py - y1)
    t = max(0.0, min(1.0, ((px - x1) * dx + (py - y1) * dy) / l2))
    proj_x = x1 + t * dx
    proj_y = y1 + t * dy
    return math.hypot(px - proj_x, py - proj_y)


def inspect_step_file(step_path: Path) -> dict:
    txt = step_path.read_text(errors="ignore")
    manifold_solids = len(re.findall(r"\bMANIFOLD_SOLID_BREP\s*\(", txt))
    advanced_faces = len(re.findall(r"\bADVANCED_FACE\s*\(", txt))
    closed_shells = len(re.findall(r"\bCLOSED_SHELL\s*\(", txt))
    nauo = len(re.findall(r"\bNEXT_ASSEMBLY_USAGE_OCCURRENCE\s*\(", txt))
    products = re.findall(r"\bPRODUCT\s*\(\s*'([^']*)'", txt)
    c2_mentions = sum(1 for p in products if "C2" in p or "0805" in p or "GRM21" in p or "CL21" in p)
    return {
        "file_size_bytes": step_path.stat().st_size,
        "manifold_solid_brep_count": manifold_solids,
        "closed_shell_count": closed_shells,
        "advanced_face_count": advanced_faces,
        "assembly_occurrence_count": nauo,
        "product_definition_count": len(products),
        "capacitor_0805_product_matches": c2_mentions,
    }


def main() -> None:
    OUT_JSON.parent.mkdir(parents=True, exist_ok=True)
    OUT_PNG.parent.mkdir(parents=True, exist_ok=True)

    export_info = json.loads(EXPORT_JSON_PATH.read_text())
    export_check = json.loads(EXPORT_CHECK_PATH.read_text())
    drc_info = json.loads(DRC_PATH.read_text())
    pcb_text = PCB_PATH.read_text()

    diag0 = export_info["diagnostics"][0]["location"]
    wx0, wx1 = float(diag0["x0"]), float(diag0["x1"])
    wy0, wy1 = float(diag0["y0"]), float(diag0["y1"])
    wz = float(diag0["z"])
    w_cx, w_cy = 0.5 * (wx0 + wx1), 0.5 * (wy0 + wy1)

    roi = (98.8, 109.5, 125.0, 136.0)
    region = parse_pcb_region(pcb_text, roi)
    step_stats = inspect_step_file(STEP_PATH)

    # Find exact vertices and edges inside or within 0.35 mm of the warning bbox
    near_vertices = []
    near_edges = []
    vbat_pts_near = []
    gnd_pts_near = []
    for poly in region["filled_polys"]:
        if poly["layer"] != "F.Cu":
            continue
        pts = poly["pts"]
        for i, (px, py) in enumerate(pts):
            if wx0 - 0.35 <= px <= wx1 + 0.35 and wy0 - 0.35 <= py <= wy1 + 0.35:
                near_vertices.append({
                    "zone": poly["zone_name"],
                    "net": poly["net"],
                    "layer": poly["layer"],
                    "vertex_index": i,
                    "x": px,
                    "y": py,
                })
            if wx0 - 1.5 <= px <= wx1 + 1.5 and wy0 - 1.5 <= py <= wy1 + 1.5:
                if poly["net"] == "VBAT":
                    vbat_pts_near.append((px, py))
                elif poly["net"] == "GND":
                    gnd_pts_near.append((px, py))
            qx, qy = pts[(i + 1) % len(pts)]
            d_center = point_to_seg_dist(w_cx, w_cy, px, py, qx, qy)
            if d_center <= 0.65:
                seg_len = math.hypot(qx - px, qy - py)
                near_edges.append({
                    "zone": poly["zone_name"],
                    "net": poly["net"],
                    "x1": px,
                    "y1": py,
                    "x2": qx,
                    "y2": qy,
                    "length_mm": round(seg_len, 6),
                    "dist_to_warning_center_mm": round(d_center, 5),
                })

    # Compute minimum F.Cu polygon vertex-to-edge clearance between VBAT and GND near the warning box
    min_vbat_gnd_gap_mm = 999.0
    for poly_v in region["filled_polys"]:
        if poly_v["layer"] != "F.Cu" or poly_v["net"] != "VBAT":
            continue
        v_pts = [p for p in poly_v["pts"] if wx0 - 2.0 <= p[0] <= wx1 + 2.0 and wy0 - 2.0 <= p[1] <= wy1 + 2.0]
        for poly_g in region["filled_polys"]:
            if poly_g["layer"] != "F.Cu" or poly_g["net"] != "GND":
                continue
            g_pts = poly_g["pts"]
            for i in range(len(g_pts)):
                gx1, gy1 = g_pts[i]
                gx2, gy2 = g_pts[(i + 1) % len(g_pts)]
                if max(gx1, gx2) < wx0 - 2.0 or min(gx1, gx2) > wx1 + 2.0:
                    continue
                if max(gy1, gy2) < wy0 - 2.0 or min(gy1, gy2) > wy1 + 2.0:
                    continue
                for vx, vy in v_pts:
                    d = point_to_seg_dist(vx, vy, gx1, gy1, gx2, gy2)
                    if d < min_vbat_gnd_gap_mm:
                        min_vbat_gnd_gap_mm = d

    # Plot 2-panel diagnostic figure
    plt.rcParams.update({
        "figure.facecolor": "#0d1117",
        "axes.facecolor": "#161b22",
        "axes.edgecolor": "#30363d",
        "axes.labelcolor": "#e6edf3",
        "text.color": "#e6edf3",
        "xtick.color": "#8b949e",
        "ytick.color": "#8b949e",
        "grid.color": "#21262d",
    })
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14.5, 6.6), dpi=160)

    net_colors = {
        "VBAT": "#ff7b72",
        "GND": "#2ea043",
        "5V_BUS": "#58a6ff",
        "SW": "#d29922",
    }

    for ax, bounds, title in [
        (ax1, (99.0, 108.8, 125.2, 135.5), "Macro View: VBAT Input Bay (MC1/MC2/MC3, C1..C4) on F.Cu"),
        (ax2, (102.4, 104.8, 130.1, 132.4), "10x Zoom: STEP OCCT Wire Self-Touch Box (z = 1.51 mm)"),
    ]:
        for poly in region["filled_polys"]:
            if poly["layer"] != "F.Cu":
                continue
            col = net_colors.get(poly["net"], "#8b949e")
            patch = MplPolygon(poly["pts"], closed=True, facecolor=col, edgecolor=col, alpha=0.30, linewidth=1.0)
            ax.add_patch(patch)
            if ax is ax2:
                pts_arr = np.array(poly["pts"])
                mask = (
                    (pts_arr[:, 0] >= bounds[0] - 0.3)
                    & (pts_arr[:, 0] <= bounds[1] + 0.3)
                    & (pts_arr[:, 1] >= bounds[2] - 0.3)
                    & (pts_arr[:, 1] <= bounds[3] + 0.3)
                )
                if np.any(mask):
                    ax.scatter(pts_arr[mask, 0], pts_arr[mask, 1], s=22, color=col, edgecolors="#ffffff", linewidths=0.5, zorder=5)

        for fp in region["footprints"]:
            for pad in fp["pads"]:
                pcol = net_colors.get(pad["net"], "#c9d1d9")
                rect = Rectangle(
                    (pad["x"] - pad["w"] / 2.0, pad["y"] - pad["h"] / 2.0),
                    pad["w"],
                    pad["h"],
                    facecolor=pcol,
                    edgecolor="#f0f6fc",
                    alpha=0.72,
                    linewidth=0.9,
                    zorder=4,
                )
                ax.add_patch(rect)
            if bounds[0] - 0.5 <= fp["x"] <= bounds[1] + 0.5 and bounds[2] - 0.5 <= fp["y"] <= bounds[3] + 0.5:
                ax.text(
                    fp["x"],
                    fp["y"],
                    fp["ref"],
                    fontsize=8.5,
                    fontweight="bold",
                    ha="center",
                    va="center",
                    color="#ffffff",
                    bbox={"boxstyle": "round,pad=0.18", "facecolor": "#0d1117", "edgecolor": "#58a6ff", "alpha": 0.85},
                    zorder=7,
                )

        for via in region["vias"]:
            c_out = Circle((via["x"], via["y"]), via["size"] / 2.0, facecolor="#d29922", edgecolor="#ffffff", alpha=0.85, zorder=6)
            c_drl = Circle((via["x"], via["y"]), via["drill"] / 2.0, facecolor="#0d1117", edgecolor="none", zorder=6.1)
            ax.add_patch(c_out)
            ax.add_patch(c_drl)

        w_rect = Rectangle(
            (wx0, wy0),
            wx1 - wx0,
            wy1 - wy0,
            facecolor="none",
            edgecolor="#ffa657",
            linewidth=2.2,
            linestyle="--",
            zorder=9,
        )
        ax.add_patch(w_rect)
        ax.set_xlim(bounds[0], bounds[1])
        ax.set_ylim(bounds[3], bounds[2])  # KiCad y-down convention
        ax.set_aspect("equal")
        ax.grid(True, alpha=0.45)
        ax.set_xlabel("KiCad Board X (mm)")
        ax.set_ylabel("KiCad Board Y (mm, +Y down)")
        ax.set_title(title, fontsize=10.5, fontweight="bold")

    ax1.annotate(
        f"Warning bbox (2x identical):\nx=[{wx0:.4f}, {wx1:.4f}]\ny=[{wy0:.4f}, {wy1:.4f}]\nz={wz:.2f} mm (F.Cu/F.Mask)",
        xy=(wx1, wy1),
        xytext=(104.3, 134.4),
        arrowprops={"arrowstyle": "->", "color": "#ffa657", "lw": 1.6},
        fontsize=8.0,
        color="#ffa657",
        bbox={"boxstyle": "round,pad=0.3", "facecolor": "#0d1117", "edgecolor": "#ffa657"},
        zorder=10,
    )
    ax2.annotate(
        f"OCCT boolean chamfer/arc\nwire tangent ({wx1 - wx0:.3f} x {wy1 - wy0:.3f} mm)\nVBAT-to-GND copper gap = {min_vbat_gnd_gap_mm:.3f} mm\n(>= 0.300 mm thermalGap, 0 DRC errors)",
        xy=(w_cx, w_cy),
        xytext=(103.68, 130.52),
        arrowprops={"arrowstyle": "->", "color": "#ffa657", "lw": 1.6},
        fontsize=8.2,
        color="#ffa657",
        bbox={"boxstyle": "round,pad=0.3", "facecolor": "#0d1117", "edgecolor": "#ffa657"},
        zorder=10,
    )

    fig.suptitle(
        "Microgoose Spine Rev A: Audit of 2 KiCad STEP Export Geometry Warnings Near C2 / C3 / MC2",
        fontsize=12.5,
        fontweight="bold",
        y=0.98,
    )
    fig.tight_layout(rect=[0, 0, 1, 0.94])
    fig.savefig(OUT_PNG, dpi=160)
    plt.close(fig)

    drc_violations = drc_info.get("violations", []) if isinstance(drc_info, dict) else []
    drc_errors = sum(1 for v in drc_violations if v.get("severity") == "error")
    drc_warnings = sum(1 for v in drc_violations if v.get("severity") == "warning")
    drc_unconnected = len(drc_info.get("unconnected_items", [])) if isinstance(drc_info, dict) else 0

    report = {
        "artifact": "kicad/microgoose-spine.export.json",
        "provenance_note": "Every numerical value is tagged with provenance: measured (from CAD/Gerber/STEP file inspection), calculated (geometric clearance computation), or specification (design rule).",
        "warning_count": {
            "value": export_info["geometryWarnings"],
            "provenance": "measured",
            "model_warnings": export_info["modelWarnings"],
            "other_warnings": export_info["otherWarnings"],
            "export_exit_code": export_info["exitCode"],
        },
        "diagnostic_bbox_mm": {
            "x0": wx0,
            "x1": wx1,
            "y0": wy0,
            "y1": wy1,
            "z": wz,
            "width_dx_mm": round(wx1 - wx0, 6),
            "height_dy_mm": round(wy1 - wy0, 6),
            "area_mm2": round((wx1 - wx0) * (wy1 - wy0), 6),
            "identical_pair": export_info["diagnostics"][0] == export_info["diagnostics"][1],
            "exact_pcb_polygon_line_range": "kicad/microgoose-spine.kicad_pcb:L32487-L32515 (zone 'VBAT solid joint at C2.1')",
            "provenance": "measured",
        },
        "nearby_footprints_mm": {
            "items": export_info["diagnostics"][0]["nearbyFootprints"],
            "footprints_parsed_in_roi": [
                {"ref": f["ref"], "value": f["value"], "x": f["x"], "y": f["y"], "rot_deg": f["rot_deg"]}
                for f in sorted(region["footprints"], key=lambda r: r["ref"])
            ],
            "provenance": "measured",
        },
        "root_cause_analysis": {
            "classification": "benign_occt_step_wire_tangent_on_fcu_pour_fillet",
            "severity": "cosmetic_cad_export_only",
            "electrical_impact": "none",
            "mechanical_impact": "none",
            "why_two_identical_warnings": (
                "kicad-cli pcb export step extrudes 2D copper/mask outlines into 3D BREP prisms using OpenCASCADE (OCCT). "
                "At x=[103.3375, 103.610018], y=[130.95, 131.5613], z=1.51 mm (the top FR4/F.Cu/F.Mask interface plane, "
                "1.05 mm southwest of C2's GND pad and along the VBAT-to-GND F.Cu pour clearance fillet), two overlapping "
                "F.Cu zone polygons ('VBAT pour' + 'VBAT solid joint' thermal fillet vs 'GND pour' clearance arc) produce a "
                "sub-micron (18 nm = 0.000018 mm in x1=103.610018) tangent vertex during boolean wire healing, emitting one "
                "warning for the F.Cu face wire and one identical warning for the conformal F.Mask opening/covering wire at z=1.51 mm."
            ),
            "rev_b_cleanup": (
                "Optional CAD hygiene for Rev B: merge 'VBAT solid joint at C2.1/C3.1' into a single 'connection: solid' "
                "setting on 'VBAT pour' or nudge the VBAT pour western/southern margin by +0.15 mm so the boolean fillet "
                "arc does not create a grazing vertex at x=103.610018."
            ),
        },
        "electrical_and_gerber_verification": {
            "min_vbat_to_gnd_fcu_clearance_near_bbox_mm": {
                "value": round(min_vbat_gnd_gap_mm, 4),
                "rule_min_clearance_mm": 0.14,
                "zone_thermal_gap_spec_mm": 0.30,
                "pass": min_vbat_gnd_gap_mm >= 0.295,
                "provenance": "calculated",
            },
            "drc_saved_fills_violations": {
                "error_count": drc_errors,
                "non_electrical_warning_count": drc_warnings,
                "unconnected_items": drc_unconnected,
                "fills_current_pass": export_check["fillsCurrent"]["pass"],
                "fills_gerbers_pass": export_check["fillsGerbers"]["pass"],
                "provenance": "measured",
            },
            "near_polygon_vertices_count": {
                "value": len(near_vertices),
                "vertices": near_vertices[:20],
                "provenance": "measured",
            },
            "near_polygon_edges": {
                "value": len(near_edges),
                "edges": near_edges[:20],
                "provenance": "calculated",
            },
        },
        "step_completeness_verification": {
            **step_stats,
            "step_written": export_info["stepWritten"],
            "all_78_fitted_bom_parts_exported": export_check["bom"]["fitted"] == 78,
            "provenance": "measured",
        },
        "plot": str(OUT_PNG.relative_to(ROOT)),
    }

    OUT_JSON.write_text(json.dumps(report, indent=2) + "\n")
    print(
        f"[step-audit] DONE: warnings={export_info['geometryWarnings']} (identical={report['diagnostic_bbox_mm']['identical_pair']}), "
        f"min_VBAT_GND_gap={min_vbat_gnd_gap_mm:.4f} mm, STEP solids={step_stats['manifold_solid_brep_count']}, "
        f"DRC violations={drc_errors}"
    )


if __name__ == "__main__":
    main()