"""Reconstruct capped threshold, box/mask scores and high-confidence replay."""
import hashlib,json
from pathlib import Path
import numpy as np
from scipy.optimize import linear_sum_assignment
from l70_cellpose import match
R=Path(__file__).resolve().parents[1];O=R/'results/l84'
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 stack(a):return np.stack([x['mask'] for x in a]) if a else np.zeros((0,512,512),bool)
def refs_bbox(ms):
 a=[]
 for m in ms:
  y,x=np.nonzero(m);a.append([float(x.min()),float(y.min()),float(x.max()+1),float(y.max()+1)])
 return np.asarray(a,dtype=np.float32).reshape(-1,4)
def iou(a,b):
 if len(a)==0 or len(b)==0:return np.zeros((len(a),len(b)),np.float32)
 wh=np.maximum(np.minimum(a[:,None,2:],b[None,:,2:])-np.maximum(a[:,None,:2],b[None,:,:2]),0);inter=wh[:,:,0]*wh[:,:,1];area=(a[:,2]-a[:,0])*(a[:,3]-a[:,1]);area2=(b[:,2]-b[:,0])*(b[:,3]-b[:,1]);union=area[:,None]+area2[None,:]-inter;return np.divide(inter,union,out=np.zeros_like(inter),where=union>0)
def box_match(refs,ids,boxes):
 mat=iou(refs,boxes);n=len(refs);m=len(boxes)
 if not n or not m:return {'matched':0,'reference_count':n,'candidate_count':m,'assignments':[]}
 weights=np.full((n,m+n),-1.,np.float64);weights[:,m:]=0;weights[:,:m]=np.where(mat>=.5,1+mat/(n+1),-1);ii,jj=linear_sum_assignment(weights,maximize=True);pairs=[{'annotation_id':int(ids[i]),'candidate_index':int(j),'iou':float(mat[i,j])} for i,j in zip(ii,jj) if j<m and mat[i,j]>=.5];return {'matched':len(pairs),'reference_count':n,'candidate_count':m,'assignments':pairs}
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 sha(R/'research/l84_confidence.py')==d['script_sha256'] and len(d['records'])==33
for f,h in p['inputs'].items():assert sha(R/f)==h
mf=[x for x in json.loads((R/'results/r95/partial/training-manifest.json').read_text())['records'] if x['hidden']];diag={r['name']:r for r in json.loads((R/'results/r95/partial/train-diagnostic/results.json').read_text())['records']};l79=json.loads((R/'results/l79/results.json').read_text())['records'];prior={r['name']:r for r in json.loads((R/'results/r95/partial/results.json').read_text())['records']};partial=json.loads((R/'results/r95/partial/training-run.json').read_text());full=json.loads((R/'results/r95/mixed/training-run.json').read_text());weights={'standard':partial['runs'][0],'oracle':partial['runs'][1],'full':full['runs'][0]}
for k,v in weights.items():assert sha(R/v['checkpoint'])==d['model_hashes'][k]==v['checkpoint_sha256']
for num,(rec,(fam,row)) in enumerate(zip(d['records'],[('train',r) for r in mf]+[('evaluation',r) for r in l79])):
 assert rec['family']==fam and sha(R/rec['source'])==rec['source_sha256'] and sha(R/rec['reference_archive'])==rec['reference_archive_sha256'] and sha(O/rec['archive'])==rec['archive_sha256'] and sha(O/rec['image'])==rec['image_sha256'];z=np.load(O/rec['archive']);refs=z['refs'];ids=z['ids'].tolist();other=np.load(R/rec['reference_archive']);expected_ids=other['ids'].tolist() if fam=='train' else other['refids'].tolist();assert np.array_equal(refs,other['refs']) and ids==expected_ids==rec['reference_ids'];rb=refs_bbox(refs)
 if fam=='train':
  old=diag[row['stem']];assert rec['name']=='train-'+row['stem'];expected_subsets={'hidden':other['hidden'].tolist(),'visible':other['visible'].tolist(),'all':list(range(len(ids)))};prior_paths={k:R/'results/r95/partial/train-diagnostic'/old['archive'] for k in weights}
 else:
  old=prior[row['name']];assert rec['name']=='eval-'+row['name'];expected_subsets={'all':list(range(len(ids)))};prior_paths={'standard':R/'results/r95/partial'/old['archive'],'oracle':R/'results/r95/partial'/old['archive'],'full':R/old['full_label_archive']}
 assert expected_subsets==rec['subsets']
 for name in ('standard','oracle','full'):
  shape=tuple(z[f'shape_{name}']);m=np.unpackbits(z[f'bits_{name}'])[:np.prod(shape)].reshape(shape).astype(bool);q=z[f'quality_{name}'];boxes=z[f'boxes_{name}'];cls=z[f'classes_{name}'];assert len(m)==len(q)==len(boxes)==len(cls)==rec['counts'][name] and len(m)<=100 and rec['hit_cap'][name]==(len(m)==100) and np.isfinite(boxes).all();order=sorted(range(len(q)),key=lambda j:(-float(q[j]),j));assert order==z[f'order_{name}'].tolist();items=[{'mask':m[j],'q':float(q[j]),'box':boxes[j]} for j in order]
  for threshold in (.001,.01,.05,.1,.25):
   eligible=[x for x in items if x['q']>=threshold];r=rec['scores'][name][str(threshold)];assert len(eligible)==r['eligible']
   for n in (10,30,'all'):
    chosen=eligible if n=='all' else eligible[:n];mm=stack(chosen);b=np.asarray([x['box'] for x in chosen],dtype=np.float32).reshape(-1,4)
    for tag,ix in expected_subsets.items():
     x=r['budgets'][str(n)][tag];assert x['box05']==box_match(rb[ix],[ids[j] for j in ix],b)
     for t in (.5,.75):assert x['mask'][str(t)]==match(refs[ix],[ids[j] for j in ix],mm,t)
  if len(m):
   a=refs.reshape(len(refs),-1).astype(np.float32);b=m.reshape(len(m),-1).astype(np.float32);inter=a@b.T;union=a.sum(1)[:,None]+b.sum(1)[None,:]-inter;mm=np.divide(inter,union,out=np.zeros_like(inter),where=union>0).max(axis=1);bb=iou(rb,boxes).max(axis=1)
  else:mm=np.zeros(len(refs));bb=np.zeros(len(refs))
  expected=[{'annotation_id':int(ids[j]),'best_mask_iou':float(mm[j]),'best_box_iou':float(bb[j])} for j in range(len(ids))];assert expected==rec['best_post_nms_oracle'][name]
  zold=np.load(prior_paths[name]);suffix=name if fam=='train' else ('12' if name=='full' else name);shape=tuple(zold[f'shape_{suffix}']);oldmask=np.unpackbits(zold[f'bits_{suffix}'])[:np.prod(shape)].reshape(shape).astype(bool);oldq=zold[f'quality_{suffix}'];oldb=zold[f'boxes_{suffix}'];oo=sorted(range(len(oldq)),key=lambda j:(-float(oldq[j]),j));new=[x for x in items if x['q']>=.25];newm=stack(new);newq=np.asarray([x['q'] for x in new]);newb=np.asarray([x['box'] for x in new],np.float32).reshape(-1,4);check={'old_count':len(oldq),'new_count':len(new),'same_masks':bool(newm.shape==oldmask[oo].shape and np.array_equal(newm,oldmask[oo])),'same_scores':bool(newq.shape==oldq[oo].shape and np.allclose(newq,oldq[oo],atol=1e-6,rtol=1e-6)),'same_boxes':bool(newb.shape==oldb[oo].shape and np.allclose(newb,oldb[oo],atol=1e-5,rtol=1e-6))};assert check==rec['high_conf_replay'][name]
 print(num+1,rec['name'],'verified',flush=True)
print('Verified 33 references/source images, three checkpoints, all post-NMS capped masks, every threshold/budget box and mask score, reference-assisted best values, and prior high-confidence comparison. Neural inference and internal NMS not rerun; matcher shared.')
