"""Reconstruct candidate bundles and scores independently from saved artifacts."""
import hashlib,json
from pathlib import Path
import numpy as np
from l70_cellpose import match
R=Path(__file__).resolve().parents[1];O=R/'results/r93'
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(1048576),b''):h.update(b)
 return h.hexdigest()
def arr(items,shape):return np.stack([x['mask'] for x in items]) if items else np.zeros((0,*shape),bool)
p=json.loads((O/'protocol.json').read_text());d=json.loads((O/'results.json').read_text());assert sha(O/'protocol.json')==d['protocol_sha256'] and len(d['records'])==45
for file,h in p['inputs'].items():assert sha(R/file)==h
l80={x['name']:x for x in json.loads((R/'results/l80/results.json').read_text())['records']};l70={x['filename'].removesuffix('.png'):x for x in json.loads((R/'results/l70/sam-results.json').read_text())['records']};c70={x['filename'].removesuffix('.png'):x for x in json.loads((R/'results/l70/results.json').read_text())['records']};dup=json.loads((R/'results/r82/label-audit.json').read_text())['duplicate_geometry_groups'];skip={v for g in dup for v in sorted(g['annotation_ids'])[1:]};dupsets={tuple(sorted(g['annotation_ids'])) for g in dup};aud={x['image_id']:x for x in json.loads((R/'results/r82/annotation-audit.json').read_text())['records']}
for r in d['records']:
 assert sha(R/r['source'])==r['source_sha256'] and sha(R/r['sam_archive'])==r['sam_archive_sha256'] and sha(R/r['cellpose_archive'])==r['cellpose_archive_sha256'] and sha(O/r['image'])==r['image_sha256'];z=np.load(R/r['cellpose_archive']);raw=np.load(R/r['sam_archive']);family=r['family'];shape=tuple(raw['mask_shape']);bits='baseline_bits' if family=='gunduz' else 'mask_bits';m=np.unpackbits(raw[bits])[:np.prod(shape)].reshape(shape).astype(bool)
 if family=='gunduz':names=['sam:'+f'{x}-{y}' for x,y in raw['points'].tolist()];rank=l80[r['name']]['rankings']['original'];ids=z['refids'].tolist()
 elif family=='khanom':names=['sam:'+str(x) for x in raw['ids'].tolist()];rank=l80[r['name']]['rankings']['original'];ids=z['annotation_ids'].tolist()
 else:
  name=r['name'].removeprefix('human-');names=raw['ids'].tolist();rank=l70[name]['rankings']['sam_first'];ids=z['annotation_ids'].tolist()
 lookup={n:{'id':n,'source':'sam','mask':v} for n,v in zip(names,m)};labels=z['labels'];lookup.update({'cellpose:'+str(j):{'id':'cellpose:'+str(j),'source':'cellpose','mask':labels==j} for j in z['candidate_labels'].tolist()});items=[lookup[n] for n in rank];assert len(items)==r['candidate_count'] and len(set(rank))==len(rank);refs=z['refs']
 if family!='human':
  pairids=l80[r['name']]['pair_ids'];refsets={'all':list(range(len(ids)))};ix=[i for i,x in enumerate(ids) if x in pairids]
  if ix:refsets['weak_pair']=ix
 else:
  cp=c70[name];severe=set()
  for pair in aud[cp['image_id']]['pairs']:
   if pair['fraction_smaller']>=.5 and tuple(sorted(pair['annotation_ids'])) not in dupsets:severe.update(pair['annotation_ids'])
  refsets={'published':list(range(len(ids))),'collapsed':[i for i,x in enumerate(ids) if x not in skip],'severe':[i for i,x in enumerate(ids) if x in severe and x not in skip]}
 assert {k:len(v) for k,v in refsets.items()}==r['refset_counts']
 for key,t in [('08',.8),('095',.95)]:
  primary=[];bundles=[];links=[]
  for x in items:
   hit=None;val=0.
   for j,y in enumerate(primary):
    if x['source']==y['source']:continue
    inter=np.count_nonzero(x['mask']&y['mask']);union=np.count_nonzero(x['mask']|y['mask']);val=inter/union if union else 0.
    if val>=t:hit=j;break
   if hit is None:primary.append(x);bundles.append([x])
   else:bundles[hit].append(x);links.append({'candidate':x['id'],'anchor':primary[hit]['id'],'iou':val,'semantics':'ranking_deferral_not_identity'})
  pol=r['policies'][key];assert [[v['id'] for v in b] for b in bundles]==pol['groups'] and links==pol['links'];assert sorted(v['id'] for b in bundles for v in b)==sorted(rank)
  for n in (5,10,30,'all'):
   chosen=bundles if n=='all' else bundles[:n];expanded=[x for b in chosen for x in b];baseline=items[:len(expanded)];score=pol['budgets'][str(n)];assert score['groups_opened']==len(chosen) and score['masks_examined']==len(expanded)
   for method,sel in [('grouped',expanded),('flat_equal_masks',baseline)]:
    masks=arr(sel,refs.shape[1:])
    for tag,ix in refsets.items():
     for t2 in (.5,.75):assert match(refs[ix],[ids[i] for i in ix],masks,t2)==score[method][tag][str(t2)]
toy=np.load(R/'results/r71/masks.npz');refs=toy['near_coincident_perfect_refs'].astype(bool);pred=toy['near_coincident_perfect_preds'].astype(bool);inter=np.count_nonzero(pred[0]&pred[1]);union=np.count_nonzero(pred[0]|pred[1]);assert .8<=inter/union<.95
for first,info in d['toy'].items():
 second='cellpose' if first=='sam' else 'sam';expected=[first+':true0',second+':true1'];assert info['groups'][0]==expected and info['first_group_mask_cost']==2 and info['first_group_score']==match(refs,[0,1],pred,.5) and info['flat_equal_masks']==match(refs,[0,1],pred,.5)
print('Verified 45 source and prediction archives, every candidate and bundle, anchor links, actual expanded-mask costs, all subset scores and both toy source orders; matching helper shared with experiment.')
