main
John Lauer Record exact-part catalog audit, Q1 fit finding, reviewed model clip and verified automatic continuation 091557c
"""Compare exact catalog assets with board24; differences require review, not automatic rejection."""
import json,subprocess,hashlib,math
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
import sexp
root=Path(__file__).resolve().parents[1];out=root/'design/component-catalog-audit';boardfile=root/'aiflow/run/board-24.kicad_pcb'
board=sexp.parse(boardfile.read_text());fps={next(x[2] for x in sexp.find(fp,'property') if x[1]=='Reference'):fp for fp in sexp.find(board,'footprint')}
groups=json.loads((out/'report.json').read_text())['groups']
def pads(fp):
 r=[]
 for p in sexp.find(fp,'pad'):
  if not p[1]:continue
  at=sexp.first(p,'at');size=sexp.first(p,'size');drill=sexp.first(p,'drill')
  r.append({'number':str(p[1]),'type':str(p[2]),'shape':str(p[3]),'xy':[float(at[1]),float(at[2])],'size':[float(x) for x in size[1:3]],'drill':[str(x) for x in drill[1:]] if drill else []})
 return sorted(r,key=lambda x:(x['number'],x['xy']))
def compare(a,b):
 if [x['number'] for x in a]!=[x['number'] for x in b]:return {'padNumberMultiset':'different','boardPadCount':len(a),'catalogPadCount':len(b)}
 # Compare translation-invariant spacing, not absolute origin or native placement rotation.
 spacing=lambda p:sorted(round(math.dist(x['xy'],y['xy']),3) for i,x in enumerate(p) for y in p[i+1:])
 return {'padNumberMultiset':'same','pairwiseSpacing':'same' if spacing(a)==spacing(b) else 'different','padTypes':'same' if [x['type'] for x in a]==[x['type'] for x in b] else 'different','sizeMultiset':'same' if sorted(sorted(x['size']) for x in a)==sorted(sorted(x['size']) for x in b) else 'different','drillMultiset':'same' if sorted(x['drill'] for x in a)==sorted(x['drill'] for x in b) else 'different'}
def check(g):
 matches=g.get('exactIdentityMatches',[])
 if len(matches)!=1:return {'mpn':g['mpn'],'references':g['references'],'status':'no-unique-exact-page'}
 m=matches[0];repo=m['url'].split('wiki.adom.inc/')[-1];d=out/'assets'/repo.split('/')[-1];d.mkdir(parents=True,exist_ok=True);assets={};errors=[]
 for kind in ['symbol','footprint']:
  path=m.get('parts',{}).get(kind)
  if not path:errors.append('no '+kind+' declared');continue
  dest=d/Path(path).name
  r=subprocess.run(['adom-wiki','repo','show',repo,path,'--out',str(dest),'--json'],capture_output=True,text=True,timeout=60)
  if r.returncode:errors.append(kind+' fetch failed: '+r.stderr[:200]);continue
  assets[kind]={'file':str(dest.relative_to(root)),'sha256':hashlib.sha256(dest.read_bytes()).hexdigest()}
 row={'mpn':g['mpn'],'references':g['references'],'wikiPage':m['url'],'assets':assets,'errors':errors,'qualification':'not established'}
 if 'footprint' in assets:
  try:
   cp=pads(sexp.parse((root/assets['footprint']['file']).read_text()));row['catalogPads']=cp;row['boardComparisons']={ref:compare(pads(fps[ref]),cp) for ref in g['references']}
  except Exception as e:errors.append('footprint parse/compare: '+str(e))
 if 'symbol' in assets:
  try:
   syms=sexp.lib_symbols(root/assets['symbol']['file']);row['catalogSymbols']={name:[{'number':x[0],'name':x[1]} for x in sexp.pins(sym)] for name,sym in syms.items()}
  except Exception as e:errors.append('symbol parse: '+str(e))
 return row
with ThreadPoolExecutor(max_workers=4) as pool:rows=list(pool.map(check,groups))
report={'board':str(boardfile.relative_to(root)),'boardSha256':hashlib.sha256(boardfile.read_bytes()).hexdigest(),'scope':'Catalog symbol/pad retrieval and translation-invariant geometry screening. No manufacturer dimensional or pin-function qualification, model visual acceptance, or automatic gate pass. Geometry differences may be intentional variants.','groups':rows}
(out/'geometry-screen.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({'groups':len(rows),'fetched':sum(bool(x.get('assets')) for x in rows),'errors':sum(bool(x.get('errors')) for x in rows),'differences':[{ 'mpn':x['mpn'],'comparisons':x['boardComparisons']} for x in rows if any('different' in c.values() for c in x.get('boardComparisons',{}).values())]}))