"""Independently rebuild deferral ordering and one-to-one scores from saved candidates."""
import hashlib,json
from pathlib import Path
import numpy as np
from l80_deferral import candidates
from l70_cellpose import match
R=Path(__file__).resolve().parents[1];O=R/'results/l80'
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()
p=json.loads((O/'protocol.json').read_text());data=json.loads((O/'results.json').read_text());assert sha(O/'protocol.json')==data['protocol_sha256'] and len(data['records'])==39
for path,digest in p['input_sha256'].items():assert sha(R/path)==digest
k=json.loads((R/'results/r92/khanom/results.json').read_text())['records'];l=json.loads((R/'results/l79/results.json').read_text())['records'];old={'r84':json.loads((R/'results/r84/results.json').read_text())['records'],'r85':json.loads((R/'results/r85/results.json').read_text())['records'],'real':{r['id']:r for r in json.loads((R/'results/r91/results.json').read_text())['records']},'synthetic':{(r['pair'],r['condition']):r for r in json.loads((R/'results/r91/synthetic/results.json').read_text())['records']}}
for rec,(family,row) in zip(data['records'],[('khanom',r) for r in k]+[('gunduz',r) for r in l]):
 refs,ids,mix,rgb,src,arch,category,pairids,previous=candidates(row,family,old);assert rec['name']==family+'-'+row['name'] and sha(O/rec['image'])==rec['image_sha256'] and rec['pair_ids']==pairids;allids=[x['id'] for x in mix];assert len(allids)==len(set(allids));orders={'original':mix}
 for name,t in [('defer08',.8),('defer095',.95)]:
  head=[];tail=[];links=[]
  for x in mix:
   anchor=None;iou=0.
   for y in head:
    if x['source']==y['source']:continue
    inter=np.count_nonzero(x['mask']&y['mask']);union=np.count_nonzero(x['mask']|y['mask']);iou=inter/union if union else 0.
    if iou>=t:anchor=y;break
   if anchor is None:head.append(x)
   else:tail.append(x);links.append({'candidate':x['id'],'anchor':anchor['id'],'iou':iou,'semantics':'ranking_deferral_not_identity'})
  orders[name]=head+tail;assert links==rec['links'][name]
 for name,items in orders.items():
  assert [x['id'] for x in items]==rec['rankings'][name] and sorted(x['id'] for x in items)==sorted(allids)
  for b in (5,10,30,'all'):
   chosen=items if b=='all' else items[:b];arr=np.stack([x['mask'] for x in chosen]) if chosen else np.zeros((0,512,512),bool)
   for t in (.5,.75):assert match(refs,ids,arr,t)==rec['scores'][name][str(b)][str(t)]
  ix=[i for i,id in enumerate(ids) if id in pairids]
  if ix:
   arr=np.stack([x['mask'] for x in items[:10]]) if items else np.zeros((0,512,512),bool)
   for t in (.5,.75):assert match(refs[ix],[ids[i] for i in ix],arr,t)==rec['pair_scores_top10'][name][str(t)]
toy=data['toy_near_coincident'];assert toy['original']['top2']['matched']==2 and toy['defer08']['top2']['matched']==1 and toy['defer08']['all']['matched']==2 and toy['defer095']['top2']['matched']==2
print('Verified 39 candidate streams, every ranking and link, retained IDs, all budget scores and near-coincident counterexample. Neural inference was not repeated; loaders and matching helper are shared with the replay.')
