main
John Lauer Save native two-sided contact artwork and recorded GLB material correction; qualification remains open 57e2489
#!/usr/bin/env python3
"""Route explicit bottom-side association leaders for distant text groups.

Targets are the mirrored projections of front-side component bodies, not exposed
electrical pads. This remains a proposal until native DRC and visual review.
"""
import heapq,itertools,json,math
from pathlib import Path
import numpy as np
from shapely import contains_xy
from shapely.geometry import box,LineString,Point
from shapely.ops import unary_union
from sexp import parse,find,first

ROOT=Path(__file__).resolve().parents[1];P=ROOT/'design/silkscreen-review'
spec=json.loads((P/'bottom-candidates.json').read_text());layout=json.loads((P/'bottom-layout.json').read_text());assert not layout['unresolved']
anchors={g['id']:g['anchor'] for g in spec['labels']}
bodies={r['ref']:r['boundsMm'] for r in json.loads((ROOT/'mechanical/cooling-680-body-audit.json').read_text())['rows']}
pad_targets={}
for footprint in find(parse((ROOT/'kicad/adom-custom-electronic-load.kicad_pcb').read_text()),'footprint'):
    ref=next(p[2] for p in find(footprint,'property') if p[1]=='Reference');at=first(footprint,'at');theta=math.radians(-float(at[3])) if len(at)>3 else 0
    pad_targets[ref]=[]
    for p in find(footprint,'pad'):
        local=first(p,'at');x,y=map(float,local[1:3]);pad_targets[ref].append([float(at[1])+x*math.cos(theta)-y*math.sin(theta),float(at[2])+x*math.sin(theta)+y*math.cos(theta)])
targets={t['reference']:t for t in json.loads((P/'bottom-association-targets.json').read_text())}
obstacles=[box(*o['box']) for o in spec['obstacles'] if o['kind']!='association-target']
obstacles += [box(*b) for g in layout['placements'] for b in g['boxes']]
pitch=.1;x0,y0,x1,y1=spec['bounds'];nx=int((x1-x0)/pitch)+1;ny=int((y1-y0)/pitch)+1
xs=x0+np.arange(nx)*pitch;ys=y0+np.arange(ny)*pitch;xx,yy=np.meshgrid(xs,ys)
def cell(p):return (round((p[0]-x0)/pitch),round((p[1]-y0)/pitch))
def point(c):return [float(xs[c[0]]),float(ys[c[1]])]
leaders=[];failed=[]
groups=sorted((g for g in layout['placements'] if math.dist(g['position'],anchors[g['id']])>3.5),key=lambda g:-math.dist(g['position'],anchors[g['id']]))
for g in groups:
    ref=g['id'];b=g['box'];a=anchors[ref];body=bodies.get(ref)
    if not body:failed.append(dict(reference=ref,reason='No fitted-body projection'));continue
    # 0.12 mm line: 0.06 mm half-stroke plus 0.06 mm edge separation.
    # This is distinct from the larger text-box reservation. No hole is crossed.
    local_obstacles=obstacles+[box(*o['box']) for o in spec['obstacles'] if o['kind']=='association-target' and o['reference']!=ref]
    occupied=unary_union(local_obstacles).buffer(.12)
    blocked=contains_xy(occupied,xx,yy)
    # Candidate starts around text enclosure; targets on the part-body projection.
    def perimeter(q,gap=0):
        x,y,X,Y=q;out=[]
        for t in np.linspace(0,1,max(8,int(2*((X-x)+(Y-y))/pitch))):
            out.extend([[x-gap+(X-x+2*gap)*t,y-gap],[x-gap+(X-x+2*gap)*t,Y+gap],[x-gap,y-gap+(Y-y+2*gap)*t],[X+gap,y-gap+(Y-y+2*gap)*t]])
        return {cell(p) for p in out}
    def free(c):return 0<=c[0]<nx and 0<=c[1]<ny and not blocked[c[1],c[0]]
    starts={c for c in perimeter(b,.35) if free(c)}
    targetbox=[body[0],body[1],body[3],body[4]]
    if ref in targets:
        goals={cell(targets[ref]['point'])} if free(cell(targets[ref]['point'])) else set()
    else:
        goals={cell([x,y]) for x in np.arange(targetbox[0],targetbox[2]+.001,.1) for y in np.arange(targetbox[1],targetbox[3]+.001,.1) if free(cell([x,y]))}
    if not starts or not goals:failed.append(dict(reference=ref,reason='No clear label rim or projected-body target',startCount=len(starts),targetCount=len(goals)));continue
    goal_array=list(goals)
    def heuristic(c):return min(abs(c[0]-t[0])+abs(c[1]-t[1]) for t in goal_array)
    heap=[];distance={};parents={};counter=itertools.count()
    for c in starts:distance[c]=0;heapq.heappush(heap,(heuristic(c),next(counter),c))
    end=None
    while heap:
        _,_,c=heapq.heappop(heap)
        if c in goals:end=c;break
        for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
            n=(c[0]+dx,c[1]+dy)
            if not free(n):continue
            cost=distance[c]+1
            if cost<distance.get(n,math.inf):distance[n]=cost;parents[n]=c;heapq.heappush(heap,(cost+heuristic(n),next(counter),n))
    if end is None:failed.append(dict(reference=ref,reason='No collision-free grid path'));continue
    path=[end]
    while path[-1] in parents:path.append(parents[path[-1]])
    path=list(reversed(path));line=LineString([point(c) for c in path]).simplify(.001)
    # Independent continuous-distance check; reject cell-sampling shortcuts.
    clearance=min(line.distance(o) for o in local_obstacles)
    if clearance<.119:failed.append(dict(reference=ref,reason='Continuous clearance failed',clearance=clearance));continue
    points=[list(p) for p in line.coords]
    leaders.append(dict(reference=ref,layer='B.SilkS',stroke=.12,points=points,targetProjection=targetbox,allowedPadProjections=pad_targets.get(ref,[]),minimumObstacleDistanceMm=clearance,labelOffsetMm=math.dist(g['position'],a)))
    obstacles.append(line.buffer(.06))
result=dict(status='proposal-not-native-accepted',boardSha256=spec['boardSha256'],layoutSha256=__import__('hashlib').sha256((P/'bottom-layout.json').read_bytes()).hexdigest(),leaders=leaders,unresolved=failed,limits=['Leaders indicate projected front-side body locations on the bottom; not exposed pad identities.','Orthogonal lines are a routing proposal; rounded corners and final artwork/association review remain pending.','Native DRC is still required for text plus leaders together.'])
(P/'bottom-leaders.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(dict(routed=len(leaders),unresolved=failed),indent=2))
raise SystemExit(2 if failed else 0)