"""Rebuild source components, saved candidate selection and all R97 scores."""
import hashlib,json,xml.etree.ElementTree as ET
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from diatom_pilot.mask_component_guard import candidates_from_binary
from l70_cellpose import match
R=Path(__file__).resolve().parents[1];O=R/'results/r97';D=R/'datasets/r80-gunduz'
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 masks(z,key,shape):
 s=tuple(z[shape]);return np.unpackbits(z[key])[:np.prod(s)].reshape(s).astype(bool)
def resize(m):
 a=np.zeros((512,512),bool);a[64:448]=cv2.resize(m.astype('uint8'),(512,384),interpolation=cv2.INTER_NEAREST)>0;return a
def stack(a):return np.stack([x['mask'] for x in a]) if a else np.zeros((0,512,512),bool)
p=json.loads((O/'protocol.json').read_text());d=json.loads((O/'results.json').read_text());screen=json.loads((O/'source-screen.json').read_text())
assert sha(O/'protocol.json')==d['protocol_sha256']==screen['protocol_sha256'] and sha(O/'source-screen.json')==d['source_screen_sha256'] and sha(R/'research/r97_replay.py')==d['script_sha256'] and sha(R/'research/r97_source_screen.py')==screen['script_sha256']
assert sha(R/p['model'])==p['model_sha256'] and sha(Path(p['sam_checkpoint']))==p['sam_sha256']
for f,h in p['inputs'].items():assert sha(R/f)==h
rows=[x for x in screen['records'] if not x['quarantined']];assert len(screen['records'])==24 and len(rows)==len(d['records'])==23
baseline={x['id']:x for x in json.loads((R/'results/r80/baseline.json').read_text())['records']};history={x['id']:x for x in json.loads((R/'results/r80/results.json').read_text())['records']}
for i,(r,s) in enumerate(zip(d['records'],rows)):
 ident=r['id'];assert ident==s['id'] and sha(O/r['archive'])==r['archive_sha256'] and sha(O/r['image'])==r['image_sha256']
 for kind,folder in [('image','images'),('mask','masks'),('xml','xml')]:
  f=D/folder/(ident+('.xml' if kind=='xml' else '.png'));assert sha(f)==r['source_'+kind+'_sha256']==s['source_'+kind+'_sha256']
 binary=np.asarray(Image.open(D/'masks'/f'{ident}.png').convert('L'))>0;root=ET.parse(D/'xml'/f'{ident}.xml').getroot();boxes=[[int(o.findtext('./bbox/'+k)) for k in ('xmin','ymin','xmax','ymax')] for o in root.findall('./objects/object')];v=candidates_from_binary(binary,boxes,minimum_area=20,containment=.98);assert v['status']=='structural_match' and v['instances']==baseline[ident]['instances'];_,cc=cv2.connectedComponents(binary.astype('uint8'),connectivity=8);refs=np.stack([resize(cc==x['component_label']) for x in v['instances']]);ids=[x['box_index'] for x in v['instances']];z=np.load(O/r['archive']);assert np.array_equal(refs,z['refs']) and ids==z['ids'].tolist() and len(refs)==r['references']
 ym=masks(z,'yolo_bits','yolo_shape');q=z['quality'];b=z['boxes'];order=sorted(range(len(q)),key=lambda j:(-float(q[j]),j));assert order==z['order'].tolist() and len(ym)==len(q)==len(b)==len(z['classes'])==r['yolo_output_count']<=100 and r['hit_yolo_cap']==(len(ym)==100)
 selected=[]
 for j in order:
  box=np.clip(b[j],0,511).astype('float64')
  if float(q[j])<.001 or box[2]-box[0]<1 or box[3]-box[1]<1:continue
  selected.append({'id':f'yolo:{j}','index':j,'box':box.tolist(),'mask':ym[j]})
  if len(selected)==30:break
 sm=masks(z,'sam_bits','sam_shape');assert len(selected)==len(sm)==len(z['sam_quality'])==r['prompt_count'] and [x['index'] for x in selected]==z['selected_indices'].tolist() and [x['box'] for x in selected]==z['clipped_boxes'].tolist()
 refined=[{'id':f"sam:{x['index']}",'mask':sm[j]} for j,x in enumerate(selected)];both=[a for j in range(len(selected)) for a in (selected[j],refined[j])];h=history[ident];assert sha(R/'results/r80'/h['sam_archive'])==h['sam_archive_sha256']==r['historical_sam_archive_sha256'] and sha(R/'results/r80'/h['cellpose_archive'])==h['cellpose_archive_sha256']==r['historical_cp_archive_sha256'];old=np.load(R/'results/r80'/h['sam_archive']);oldm=masks(old,'mask_bits','mask_shape');lookup=dict(zip(old['ids'].tolist(),oldm));cp=np.load(R/'results/r80'/h['cellpose_archive'])['labels'];historical=[]
 for name in h['rankings']['sam_first']:
  typ,sub=name.split(':',1);historical.append({'id':name,'mask':resize(lookup[sub] if typ=='sam' else cp==int(sub))})
 assert len(historical)==r['historical_count']
 for name,items in [('yolo',selected),('sam_box',refined),('both',both),('historical',historical)]:
  assert [x['id'] for x in items]==r['rankings'][name]
  for budget in (10,30,'all'):
   for threshold in (.5,.75):assert match(refs,ids,stack(items if budget=='all' else items[:budget]),threshold)==r['scores'][name][str(budget)][str(threshold)]
 print(i+1,ident,'verified',flush=True)
print('Verified source hashes and structural mapping, retained files, archives, candidate selection and all scores. Shared matcher; inference not rerun.')
