"""Retrospective label-free ranking of paired masks, same candidate pool."""
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/l85'
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 unpack(z,b,s):
 shape=tuple(z[s]);return np.unpackbits(z[b])[:np.prod(shape)].reshape(shape).astype(bool)
p=json.loads((O/'protocol.json').read_text())
for f,h in p['inputs'].items():assert sha(R/f)==h
records=[]
for source in ('r96','r97'):
 for r in json.loads((R/f'results/{source}/results.json').read_text())['records']:
  z=np.load(R/f'results/{source}'/r['archive']);assert sha(R/f'results/{source}'/r['archive'])==r['archive_sha256']
  if source=='r96':
   old=np.load(R/r['l84_archive']);assert sha(R/r['l84_archive'])==r['l84_archive_sha256'];ym=unpack(old,'bits_standard','shape_standard')[z['yolo_indices']];sm=unpack(z,'mask_bits','mask_shape');q=z['sam_quality'];ix=r['subsets']['hidden'] if r['family']=='train' else r['subsets']['all'];refs=old['refs'][ix];ids=[int(old['ids'][j]) for j in ix];name=r['name'];group='hidden training' if r['family']=='train' else r['category'];condition=r['condition']
  else:
   allm=unpack(z,'yolo_bits','yolo_shape');ym=allm[z['selected_indices']];sm=unpack(z,'sam_bits','sam_shape');q=z['sam_quality'];refs=z['refs'];ids=z['ids'].tolist();name=r['id'];group='R97 real';condition=None
  assert len(ym)==len(sm)==len(q)==r['prompt_count'];a=ym.reshape(len(ym),-1);b=sm.reshape(len(sm),-1);inter=np.logical_and(a,b).sum(1);union=np.logical_or(a,b).sum(1);agreement=np.divide(inter,union,out=np.zeros(len(inter),dtype=float),where=union>0);ranking={'confidence':list(range(len(sm))),'mask_agreement':sorted(range(len(sm)),key=lambda j:(-float(agreement[j]),j)),'sam_quality':sorted(range(len(sm)),key=lambda j:(-float(q[j]),j))};scores={}
  for policy,order in ranking.items():
   scores[policy]={}
   for budget in (5,10,20,30):
    scores[policy][str(budget)]={str(t):match(refs,ids,sm[order[:budget]],t) for t in (.5,.75)}
  records.append({'source':source,'name':name,'group':group,'condition':condition,'archive':r['archive'],'archive_sha256':r['archive_sha256'],'references':len(refs),'candidate_count':len(sm),'agreement':agreement.tolist(),'sam_quality':q.tolist(),'rankings':ranking,'scores':scores})
  print(source,name,'done',flush=True)
(O/'results.json').write_text(json.dumps({'protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':records},indent=2)+'\n')
