"""Nominal attachment graph; geometric contact is not bond strength or preload."""
from audit_functional_28 import *

def main():
 M,I=load();eligible=[q for q in I.values() if q.kind!='flexible_route'];edges=[];tol=.002
 # Build a sufficient contact graph, avoiding redundant expensive distances
 # between groups already connected. Simple pad/bond interfaces are tested first.
 parents={q.name:q.name for q in eligible}
 def group(n):
  while parents[n]!=n:parents[n]=parents[parents[n]];n=parents[n]
  return n
 seeds=[n for n in I if n.startswith(('C27_R2_01_','C27_R2_02_'))]
 for n in seeds[1:]:parents[n]=seeds[0]
 pairs=[(len(a.s.faces())+len(c.s.faces()),a,c)for a,c in itertools.combinations(eligible,2)if boxdistance(a.bb,c.bb)<=tol]
 for _,a,c in sorted(pairs,key=lambda v:v[0]):
  if group(a.name)==group(c.name):continue
  print('CONTACT_CHECK',a.name,c.name,flush=True)
  # Contact can only occur within the shared bounds. Clip to this exact
  # local region before measuring; this avoids distant toroidal shell faces.
  lo=[max(a.bb[i],c.bb[i])-.01 for i in [0,2,4]]
  hi=[min(a.bb[i],c.bb[i])+.01 for i in [1,3,5]]
  region=b.Solid.make_box(*(hi[i]-lo[i] for i in range(3)),b.Plane(origin=lo))
  aa=norm(a.s.intersect(region));cc=norm(c.s.intersect(region))
  if volume(aa)<1e-10 or volume(cc)<1e-10:continue
  d=distance(Item(a.name,aa,a.kind),Item(c.name,cc,c.kind))
  if d<=tol:
   edges.append({'a':a.name,'b':c.name,'distance_mm':d});parents[group(a.name)]=group(c.name)
  if len({group(q.name)for q in eligible})==1:break
 anchored={q.name for q in eligible if group(q.name)==group(seeds[0])}
 unconnected=[q.name for q in eligible if q.name not in anchored]
 result={'method':'exact minimum shape distances in shared bounds plus 0.01mm margin, 0.002mm contact tolerance; sufficient spanning contact graph to front or rear shell, redundant within-group distances omitted','edges':edges,'unconnected':unconnected,'custom_component_count':len([q for q in eligible if q.kind not in ('electronics','fastener')]),'qualification_limit':'Geometric contact is not retention strength. Screws and bonded/compliant interfaces require specified assembly and physical tests. Mesh is represented by rods as one stock panel; leads are excluded from rigid attachment graph.'}
 (ROOT/'audit/Concept_28_R1_attachment_graph.json').write_text(json.dumps(result,indent=2));print('ATTACHMENT',len(edges),'edges; unconnected:',unconnected,flush=True)
if __name__=='__main__':main()
