main
John Lauer Save native two-sided contact artwork and recorded GLB material correction; qualification remains open 57e2489
#!/usr/bin/env python3
"""Plan front contact legends using native metrics and fitted-body exclusions."""
import json,subprocess,hashlib,math,copy
from pathlib import Path
from shapely.geometry import box,LineString,Polygon
from shapely.ops import unary_union
from sexp import parse,find,first
R=Path(__file__).resolve().parents[1];P=R/'design/silkscreen-review';O=P/'front-contacts';O.mkdir(exist_ok=True)
boardpath=R/'kicad/adom-custom-electronic-load.kicad_pcb';board=parse(boardpath.read_text());oldgeom=json.loads((P/'geometry.json').read_text());bottom=json.loads((P/'bottom-layout.json').read_text());groups=[copy.deepcopy(g) for g in bottom['placements'] if g['id'] in ['J'+str(i) for i in range(1,8)]+['MP'+str(i) for i in range(1,5)]]
newtexts=[]
corner_y={c['role']:c['y'] for g in groups if g['id']=='MP3' for c in g['children']}
for g in groups:
 for c in g['children']:
  c['layer']='F.SilkS';c['mirrored']=False
  if g['id']=='J7':
   # The fitted inductor ends at Y=98.2: there is no legal two-line
   # legend above this contact. Put its paired legend beside its rim.
   c['x']=145.65 if c['role']=='reference' else 148.0;c['y']=100.8;c['size']=.8;c['angle']=0
  if g['id']=='MP4':c['y']=corner_y[c['role']]
  newtexts.append(c)
existing=[]
for fp in find(board,'footprint'):
 at=first(fp,'at');angle=-math.radians(float(at[3]) if len(at)>3 else 0)
 for p in find(fp,'property'):
  if first(p,'layer')[1]!='F.SilkS' or first(p,'hide')==['hide','yes']:continue
  e=first(p,'effects');font=first(e,'font');sz=first(font,'size');a=first(p,'at');x,y=map(float,a[1:3]);just=first(e,'justify') or []
  existing.append(dict(text=p[2],x=float(at[1])+x*math.cos(angle)-y*math.sin(angle),y=float(at[2])+x*math.sin(angle)+y*math.cos(angle),height=float(sz[1]),width=float(sz[2]),stroke=float(first(font,'thickness')[1]),rotation=float(a[3]) if len(a)>3 else 0,mirrored='mirror' in just,align='center'))
for p in find(board,'gr_text'):
 if first(p,'layer')[1]!='F.SilkS':continue
 a=first(p,'at');e=first(p,'effects');f=first(e,'font');sz=first(f,'size');existing.append(dict(text=p[1],x=float(a[1]),y=float(a[2]),height=float(sz[1]),width=float(sz[2]),stroke=float(first(f,'thickness')[1]),rotation=float(a[3]) if len(a)>3 else 0,mirrored=False,align='center'))
field_moves=[]
for e in existing:
 if e['text']=='J8':
  field_moves.append(dict(reference='J8',before=[e['x'],e['y']],after=[156.5,e['y']]))
  e['x']=156.5
assert len(field_moves)==1
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']
all_defs=[dict(text=c['text'],x=c['x'],y=c['y'],height=c['size'],width=c['size'],stroke=c['stroke'],rotation=c.get('angle',0),mirrored=False,align='center') for c in newtexts]+existing
bounds={}
for start in range(0,len(all_defs),40):
 defs=[dict(v,id=str(i)) for i,v in enumerate(all_defs) if start<=i<start+40]
 r=json.loads(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=defs))],text=True));assert r['success'];bounds.update({int(t['id']):t['box'] for t in r['texts']});(O/f'metrics-{start:03}.json').write_text(json.dumps(r,indent=2)+'\n')
for i,c in enumerate(newtexts):c['box']=bounds[i]
# Original v85 pads/bodies remain valid through the independently checked chain
# of silk-only revisions. Bind that fact instead of rewriting the historic audit.
proof=json.loads((P/'bottom-landing-verification.json').read_text());assert all(proof['unchanged'].values());assert proof['savedSha256']==hashlib.sha256(boardpath.read_bytes()).hexdigest()
physical=[o for o in oldgeom['obstacles'] if o['layer']=='F.SilkS'];obstacles=[(o['id'],box(*o['box'])) for o in physical]+[('existing:'+str(i),box(*bounds[i])) for i in range(len(newtexts),len(all_defs))];findings=[]
for i,c in enumerate(newtexts):
 b=box(*c['box'])
 for name,o in obstacles:
  if b.distance(o)<.119:findings.append(dict(kind='text-obstacle',text=c['text'],reference=c['reference'],obstacle=name,distance=b.distance(o)))
 for d in newtexts[:i]:
  if b.distance(box(*d['box']))<.119:findings.append(dict(kind='text-pair',texts=[c['text'],d['text']]))
all_obstacles=unary_union([o for _,o in obstacles]+[box(*c['box']) for c in newtexts]);graphics=[];framechecks=[]
frames=json.loads((P/'bottom-contact-tags.json').read_text())['frames']+json.loads((P/'bottom-corner-tags.json').read_text())['frames']
for f in frames:
 if f['kind']=='rect':
  (x,y),(X,Y)=f['points'];y=98.8;pts=[[x,y],[X,y],[X,Y],[x,Y],[x,y]]
 else:pts=f['points']
 line=LineString(pts);clipped=line.difference(all_obstacles.buffer(.121));parts=list(clipped.geoms) if hasattr(clipped,'geoms') else [clipped];ratio=sum(p.length for p in parts)/line.length;framechecks.append(dict(reference=f['reference'],retainedFraction=ratio))
 if ratio<.7:findings.append(dict(kind='frame-too-broken',reference=f['reference'],retainedFraction=ratio))
 area=Polygon(pts)
 for o in physical:
  if o['kind']=='pad-mask-or-hole' and o.get('reference')!=f['reference'] and area.contains(box(*o['box']).representative_point()):findings.append(dict(kind='frame-encloses-other-pad',reference=f['reference'],obstacle=o['id']))
 for p in parts:
  xy=list(p.coords)
  for a,b in zip(xy,xy[1:]):
   if math.dist(a,b)>.02:graphics.append(dict(kind='line',layer='F.SilkS',points=[list(a),list(b)],stroke=.12,reference=f['reference']))
result=dict(status='candidate only',boardSha256=proof['savedSha256'],nativeRevision=state['revision'],texts=newtexts,fieldMoves=field_moves,graphics=graphics,frameChecks=framechecks,findings=findings,sourceBodyAudit='mechanical/cooling-680-body-audit.json',equivalenceEvidence='design/silkscreen-review/bottom-landing-verification.json');(O/'artwork.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(dict(texts=len(newtexts),graphics=len(graphics),findings=findings,frames=framechecks),indent=2));raise SystemExit(2 if findings else 0)