"""Post-hoc inspect paired match overlap; candidate masks belong to different planes."""
import json
from pathlib import Path
import numpy as np
R=Path(__file__).resolve().parents[1];O=R/'results/r89/opaque';rows=json.loads((O/'results.json').read_text())['records'];out=[]
for r in rows:
 z=np.load(O/r['archive']);m=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);lookup={str(i):a for i,a in zip(z['ids'],m)};item={'pair':r['pair'],'split':r['split'],'condition':r['condition'],'methods':{}}
 for method in ('middle256','middle4','focal'):
  a=r['scores'][method]['30']['assignments'];result={'matched':len(a),'assigned':a,'candidate_pair_iou':None,'each_other_silhouette_iou':[]}
  for v in a:
   mask=lookup[v['candidate_id']];other=z['refs'][v['plane'],1-v['source_id']];inter=int((mask&other).sum());union=int((mask|other).sum());result['each_other_silhouette_iou'].append({'candidate_id':v['candidate_id'],'other_source_iou':inter/union if union else 0.})
  if len(a)==2:
   x=lookup[a[0]['candidate_id']];y=lookup[a[1]['candidate_id']];union=int((x|y).sum());result['candidate_pair_iou']=int((x&y).sum())/union if union else 0
  item['methods'][method]=result
 out.append(item)
(O/'assignment-audit.json').write_text(json.dumps({'warning':'Post-hoc diagnostic; candidates may originate in different synthetic planes, and shared IoU does not prove or refute identity.','records':out},indent=2)+'\n');print([(x['pair'],x['condition'],round(x['methods']['focal']['candidate_pair_iou'],3)) for x in out if x['methods']['focal']['candidate_pair_iou'] is not None and x['methods']['focal']['candidate_pair_iou']>=.8])
