main
John Lauer Board32 finish and export evidence, selected cooling assembly review and mechanical BOM 851498a
#!/usr/bin/env python3
"""Read-only whole-board label screen using KiCad glyph bounds and fitted CAD.

This deliberately does not claim final silkscreen acceptance: artwork, leads,
label associations and assembled visibility need their own native review.
"""
import argparse
import hashlib
import importlib.util
import json
import math
from pathlib import Path
import subprocess

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'design/silkscreen-review'

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--mask-helper', required=True, type=Path)
    parser.add_argument('--live-state', required=True, type=Path)
    parser.add_argument("--board", type=Path, default=ROOT / "kicad/adom-custom-electronic-load.kicad_pcb")
    parser.add_argument("--body-audit", type=Path, default=ROOT / "mechanical/cooling-680-body-audit.json")
    parser.add_argument("--out", type=Path, default=OUT)
    args = parser.parse_args()
    output_dir = args.out
    spec = importlib.util.spec_from_file_location('native_mask', args.mask_helper)
    mask = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mask)
    board_path = args.board
    sha = hashlib.sha256(board_path.read_bytes()).hexdigest()
    board = mask.parse(board_path.read_text())
    live = json.loads(args.live_state.read_text())
    assert live['success'] and live['netsRemaining'] in (0, [])
    bodies = json.loads(args.body_audit.read_text())
    assert bodies['boardSha256'] == sha
    marks, candidates, missing_values = [], [], []
    for fp in mask.sub(board, 'footprint'):
        at = list(map(float, mask.one(fp, 'at')))
        theta = math.radians(-(at[2] if len(at) > 2 else 0))
        props = mask.sub(fp, 'property')
        ref = next(p[2] for p in props if p[1] == 'Reference')
        for p in props:
            layer = mask.one(p, 'layer')[0]
            effects = mask.one(p, 'effects')
            hidden = mask.one(p, 'hide') == ['yes'] or mask.one(effects, 'hide') == ['yes'] or 'hide' in effects
            if p[1] == 'Value' and ref.startswith(('R', 'C', 'L')) and (hidden or not layer.endswith('.SilkS')):
                missing_values.append(ref)
            if hidden or layer not in ('F.SilkS', 'B.SilkS'):
                continue
            local = list(map(float, mask.one(p, 'at')))
            x = at[0] + local[0]*math.cos(theta) - local[1]*math.sin(theta)
            y = at[1] + local[0]*math.sin(theta) + local[1]*math.cos(theta)
            font = mask.one(effects, 'font')
            size = list(map(float, mask.one(font, 'size')))
            justify = mask.one(effects, 'justify')
            row = dict(id=mask.one(p, 'uuid')[0], text=p[2], x=x, y=y,
                       height=size[0], width=size[1], stroke=float(mask.one(font, 'thickness')[0]),
                       rotation=local[2] if len(local)>2 else 0,
                       align=next((a for a in ('left','right') if a in justify), 'center'),
                       mirrored='mirror' in justify)
            candidates.append(row)
            marks.append(dict(id=row['id'], text=row['text'], reference=ref, layer=layer, **{'nativeInput':row}))
    for p in mask.sub(board, 'gr_text'):
        layer = mask.one(p, 'layer')[0]
        if layer not in ('F.SilkS','B.SilkS'): continue
        at = list(map(float, mask.one(p, 'at')))
        effects=mask.one(p,'effects');font=mask.one(effects,'font');size=list(map(float,mask.one(font,'size')))
        just=mask.one(effects,'justify')
        row=dict(id=mask.one(p,'uuid')[0],text=p[1],x=at[0],y=at[1],height=size[0],width=size[1],stroke=float(mask.one(font,'thickness')[0]),rotation=at[2] if len(at)>2 else 0,mirrored='mirror' in just,align=next((a for a in ('left','right') if a in just),'center'))
        candidates.append(row);marks.append(dict(id=row['id'],text=row['text'],reference='board',layer=layer,nativeInput=row))
    output_dir.mkdir(parents=True, exist_ok=True)
    measured=[]
    for start in range(0,len(candidates),40):
        payload=dict(filePath=live['boardPath'],expectedRevision=live['revision'],texts=candidates[start:start+40])
        raw=subprocess.check_output(['adom-bridge','--target','AdomLapper','--ai-thread','adom-custom-load','kicad_text_bounds',json.dumps(payload)],text=True)
        reply=json.loads(raw)
        assert reply['success'] and reply['mutated'] is False and reply['revision']==live['revision']
        (output_dir/f'native-metrics-{start:03}.json').write_text(raw)
        measured.extend(reply['texts'])
    boxes={r['id']:r['box'] for r in measured}
    for row in marks: row['box']=boxes[row['id']]
    obstacles=mask.obstacles(board)
    for row in bodies['rows']:
        x,y,z,X,Y,Z=row['boundsMm']
        obstacles.append(dict(id=row['ref']+':body',kind='fitted-body',layer='F.SilkS',box=[x,y,X,Y]))
    # All drilled vias are reserved on both faces, including tented ones.
    for i,v in enumerate(mask.sub(board,'via')):
        x,y=map(float,mask.one(v,'at'));r=float(mask.one(v,'drill')[0])/2
        for face in ('F','B'):
            obstacles.append(dict(id=f'via:{i}',kind='via-hole',layer=face+'.SilkS',box=[x-r,y-r,x+r,y+r]))
    def overlap(a,b): return a[0]<b[2] and b[0]<a[2] and a[1]<b[3] and b[1]<a[3]
    collisions=[dict(reference=m['reference'],text=m['text'],mark=m['id'],obstacle=o['id'],kind=o['kind'],layer=m['layer']) for m in marks for o in obstacles if m['layer']==o['layer'] and overlap(m['box'],o['box'])]
    pairs=[dict(a=a['text'],b=b['text'],layer=a['layer']) for i,a in enumerate(marks) for b in marks[i+1:] if a['layer']==b['layer'] and overlap(a['box'],b['box'])]
    result=dict(status='read-only-conservative-screen-not-acceptance',boardSha256=sha,nativeRevision=live['revision'],maskHelperSha256=hashlib.sha256(args.mask_helper.read_bytes()).hexdigest(),nativeTextCount=len(marks),obstacleCount=len(obstacles),collisions=collisions,labelPairs=pairs,passiveValuesNotOnSilkscreen=missing_values,limits=['Axis-aligned native text bounds and CAD body bounds can over-report collisions.','Mask polygons use saved-board pad transforms; footprint field rotation is board-absolute. Native visual confirmation is still required.','Existing line/arc artwork, exact hole envelopes outside mask, assembled heatsink/carrier occlusion, pin mapping, edge containment and clearances are not yet accepted.','No native board edit, thermal gate or silkscreen gate completion.'])
    (output_dir/'geometry.json').write_text(json.dumps(dict(marks=marks,obstacles=obstacles),indent=2)+'\n')
    (output_dir/'review.json').write_text(json.dumps(result,indent=2)+'\n')
    print(json.dumps({k:result[k] for k in ('status','nativeTextCount','obstacleCount')}))
    print(f'{len(collisions)} conservative obstacle intersections; {len(pairs)} text pairs; {len(missing_values)} passive values absent from silk')

if __name__ == '__main__': main()