main
John Lauer Save native two-sided contact artwork and recorded GLB material correction; qualification remains open 57e2489
#!/usr/bin/env python3
"""Plan mirrored reference/value groups from the actual board, without editing it."""
import json,math,hashlib,subprocess
from pathlib import Path
from sexp import parse,find,first

ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'design/silkscreen-review'
board_path=ROOT/'kicad/adom-custom-electronic-load.kicad_pcb';board=parse(board_path.read_text())
source=json.loads((OUT/'geometry.json').read_text())
groups=[];texts=[]
aliases={'DUT_POS':'DUT+','LOAD_POS':'LOAD+','SHUNT_P_SENSE':'SH+','SHUNT_N_SENSE':'SH-','TEMP_SENSE':'TEMP','FAN_TACH':'TACH','I_SET':'ISET','V_GATE':'VDRV','LATCH_Q':'LATCH','5V_AUX':'5V AUX'}
for f in find(board,'footprint'):
    props={p[1]:p[2] for p in find(f,'property')};ref=props['Reference'];at=first(f,'at');anchor=list(map(float,at[1:3]))
    value=None
    if ref.startswith(('R','C','L','F')):value='20m' if ref=='RSH1' else props['Value']
    elif ref.startswith(('TP','MP')) or ref in ['J'+str(i) for i in range(1,8)]:
        nets={first(p,'net')[-1] for p in find(f,'pad') if first(p,'net')}
        assert len(nets)==1,(ref,nets)
        net=next(iter(nets));value=aliases.get(net,net)
    elif ref.startswith('J'):value={'J8':'USB','J9':'FAN','J10':'TEMP','J11':'SWD'}[ref]
    children=[dict(id=ref+':reference',text=ref,height=1.0 if value else .8,width=1.0 if value else .8,stroke=.12,x=0,y=0,mirrored=True,rotation=0)]
    if value:children.append(dict(id=ref+':value',text=value,height=.8,width=.8,stroke=.12,x=0,y=0,mirrored=True,rotation=0))
    groups.append(dict(id=ref,anchor=anchor,value=value,children=children));texts.extend(children)
state=json.loads(subprocess.check_output(['adom-bridge','--target','AdomLapper','--ai-thread','adom-custom-load','kicad_routing_state',json.dumps(dict(filePath='C:/Users/john/adom-projects/adom-custom-electronic-load/kicad/adom-custom-electronic-load.kicad_pcb'))],text=True));assert state['success']
bounds={}
for start in range(0,len(texts),40):
    raw=subprocess.check_output(['adom-bridge','--target','AdomLapper','--ai-thread','adom-custom-load','kicad_text_bounds',json.dumps(dict(filePath=state['boardPath'],expectedRevision=state['revision'],texts=texts[start:start+40]))],text=True)
    r=json.loads(raw);assert r['success'];(OUT/f'bottom-native-metrics-{start:03}.json').write_text(raw)
    bounds.update({t['id']:t['box'] for t in r['texts']})
labels=[]
for g in groups:
    # Native extents, 0.2 mm clear vertical separation, reference then smaller value.
    heights=[bounds[c['id']][3]-bounds[c['id']][1] for c in g['children']]
    total=sum(heights)+.2*(len(heights)-1);base=-total/2
    offsets=[]
    for h in heights:offsets.append(base+h/2);base+=h+.2
    cs=[]
    radius=8 if g['id'] in ('R21','R3') else 6 if g['id'] in ('R17','R19','R20','R34') else 4
    for i in range(-int(radius/.4),int(radius/.4)+1):
        for j in range(-int(radius/.4),int(radius/.4)+1):
            dx,dy=i*.4,j*.4
            if math.hypot(dx,dy)>radius:continue
            x,y=g['anchor'][0]+dx,g['anchor'][1]+dy;children=[]
            for k,c in enumerate(g['children']):
                q=bounds[c['id']];yy=y+offsets[k]
                children.append(dict(text=c['text'],reference=g['id'],role='reference' if k==0 else 'value',x=x,y=yy,size=c['height'],stroke=c['stroke'],layer='B.SilkS',mirrored=True,box=[q[0]+x,q[1]+yy,q[2]+x,q[3]+yy]))
            boxes=[c['box'] for c in children]
            b=[min(q[0] for q in boxes),min(q[1] for q in boxes),max(q[2] for q in boxes),max(q[3] for q in boxes)]
            cs.append(dict(position=[x,y],font=g['children'][0]['height'],box=b,boxes=boxes,children=children,layer='B.SilkS'))
            rotated=[]
            for c in children:
                q=c['box']
                # +90 degree KiCad text rotation: clockwise screen-Y transform.
                corners=[(x+(yy-y),y-(xx-x)) for xx,yy in [(q[0],q[1]),(q[0],q[3]),(q[2],q[1]),(q[2],q[3])]]
                rotated.append(dict(c,x=x+(c['y']-y),y=y-(c['x']-x),angle=90,box=[min(a for a,b in corners),min(b for a,b in corners),max(a for a,b in corners),max(b for a,b in corners)]))
            rb=[c['box'] for c in rotated];envelope=[min(q[0] for q in rb),min(q[1] for q in rb),max(q[2] for q in rb),max(q[3] for q in rb)]
            cs.append(dict(position=[x,y],font=g['children'][0]['height'],box=envelope,boxes=rb,children=rotated,layer='B.SilkS',qualityPenalty=.1))
    labels.append(dict(id=g['id'],anchor=g['anchor'],maxDistance=radius,candidates=cs,requiredRoles=['reference','value'] if g['value'] else ['reference'],maxValueRatio=.8))
data=dict(bounds=[98.3,30.3,161.7,101.7],labels=labels,obstacles=[o for o in source['obstacles'] if o['layer']=='B.SilkS'],clearance=.12,solver='milp',solverSeconds=90,milpPerFont=192,candidatesPerLabel=2000,boundsSource='Native mirrored glyph metrics; exact electrical geometry retained from v85; rounded-corner, label association/leader and native DRC review pending',boardSha256=hashlib.sha256(board_path.read_bytes()).hexdigest(),nativeRevision=state['revision'])
(OUT/'bottom-candidates.json').write_text(json.dumps(data)+'\n')
print(f'{len(groups)} complete reference/value groups, {len(texts)} native text extents; minimum 0.8 mm matches current project rules')