"""Verify saved source references, candidate ranks, and R98 score replay."""
import json
from pathlib import Path
import numpy as np
from l70_cellpose import match
from r97_replay import sha,stack
R=Path(__file__).resolve().parents[1];O=R/'results/r98'
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());screen=json.loads((O/'source-screen.json').read_text());d=json.loads((O/'results.json').read_text());assert sha(O/'protocol.json')==screen['protocol_sha256']==d['protocol_sha256'] and sha(O/'source-screen.json')==d['screen_sha256'] and sha(R/'research/r98_replay.py')==d['script_sha256'] and sha(R/'research/r98_screen.py')==screen['script_sha256']
for f,h in p['inputs'].items():assert sha(R/f)==h
prior=json.loads((R/'results/r87/results.json').read_text())['records'];kept=[x for x in screen['records'] if not x['quarantined']];assert len(kept)==len(d['records'])==13
for r,s in zip(d['records'],kept):
 idx=r['index'];assert idx==s['index'];a=prior[idx];assert sha(R/r['source'])==r['source_sha256']==s['source_image_sha256'] and sha(R/r['prior_archive'])==r['prior_archive_sha256']==a['archive_sha256']==s['archive_sha256'] and sha(O/r['archive'])==r['archive_sha256'] and sha(O/r['image'])==r['image_sha256'];z=np.load(O/r['archive']);old=np.load(R/r['prior_archive']);refs=old['refs'];ids=old['annotation_ids'].tolist();assert np.array_equal(refs,z['refs']) and ids==z['ids'].tolist() and len(refs)==r['references'];ym=unpack(z,'yolo_bits','yolo_shape');sm=unpack(z,'sam_bits','sam_shape');q=z['quality'];boxes=z['boxes'];order=sorted(range(len(q)),key=lambda j:(-float(q[j]),j));assert order==z['order'].tolist() and len(q)==len(ym)==len(boxes)==r['yolo_count']<=100 and r['hit_cap']==(len(ym)==100);sel=[];clipped=[]
 for j in order:
  b=np.clip(boxes[j],0,511).astype('float64')
  if float(q[j])<.001 or b[2]-b[0]<1 or b[3]-b[1]<1:continue
  sel.append(j);clipped.append(b.tolist())
  if len(sel)==30:break
 assert sel==z['selected_indices'].tolist() and clipped==z['clipped_boxes'].tolist() and len(sm)==len(sel)==r['prompt_count'];sq=z['sam_quality'];quality=sorted(range(len(sm)),key=lambda j:(-float(sq[j]),j));assert quality==z['quality_order'].tolist();confidence=[{'id':f'sam:{j}','mask':m} for j,m in zip(sel,sm)];ranked=[confidence[j] for j in quality];raw=unpack(old,'mask_bits','mask_shape');lookup=dict(zip(old['ids'].tolist(),raw));history=[{'id':k,'mask':lookup[k]} for k in a['policies']['256']['ranking']]
 for name,items in [('confidence',confidence),('sam_quality',ranked),('history_grid256',history)]:
  assert [x['id'] for x in items]==r['rankings'][name]
  for n in (5,10,20,30):
   for t in (.5,.75):assert match(refs,ids,stack(items[:n]),t)==r['scores'][name][str(n)][str(t)]
 print(idx,'verified',flush=True)
print('Verified hashes, retained fields, paired selection, rankings and all scores; source references and matcher shared; no inference rerun.')
