"""Rebuild train-image reference masks and replay all withheld-label scores."""
import hashlib,json
from pathlib import Path
import cv2,numpy as np
from l70_cellpose import match
R=Path(__file__).resolve().parents[1];O=R/'results/r95/partial/train-diagnostic'
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)
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/r95_withheld_eval.py')==d['script_sha256'] and len(d['records'])==28
for f,h in p['inputs'].items():assert sha(R/f)==h
m=json.loads((R/'results/r95/partial/training-manifest.json').read_text())['records'];tr=json.loads((R/'results/r95/partial/training-run.json').read_text());full=json.loads((R/'results/r95/mixed/training-run.json').read_text());w={'standard':tr['runs'][0],'oracle':tr['runs'][1],'full':full['runs'][0]};assert all(sha(R/x['checkpoint'])==x['checkpoint_sha256']==d['model_hashes'][k] for k,x in w.items())
for r,row in zip(d['records'],m):
 assert r['name']==row['stem'] and r['image']==row['image'] and sha(R/r['image'])==r['image_sha256']==row['image_sha256'] and sha(R/r['full_label'])==r['full_label_sha256']==row['full_label_sha256'] and sha(O/r['archive'])==r['archive_sha256'] and sha(O/r['comparison'])==r['comparison_sha256'];lines=(R/r['full_label']).read_text().splitlines();ids=row['full_annotation_ids'];assert ids==r['reference_ids'] and len(lines)==len(ids);refs=[]
 for line in lines:
  v=np.asarray([float(x) for x in line.split()]);assert v[0]==0;pts=np.rint(v[1:].reshape(-1,2)*512).astype('int32');mask=np.zeros((512,512),np.uint8);cv2.fillPoly(mask,[pts],1);refs.append(mask.astype(bool))
 refs=np.stack(refs);visible=[i for i,x in enumerate(ids) if x in row['visible_annotation_ids']];hidden=[i for i,x in enumerate(ids) if row['hidden'] is not None and x==row['hidden']['annotation_id']];assert r['visible_ids']==row['visible_annotation_ids'] and r['hidden_id']==(row['hidden']['annotation_id'] if row['hidden'] else None);z=np.load(O/r['archive']);assert np.array_equal(z['refs'],refs) and z['ids'].tolist()==ids and z['visible'].tolist()==visible and z['hidden'].tolist()==hidden;subsets={'all':list(range(len(ids))),'visible':visible,'hidden':hidden}
 for name in ('standard','oracle','full'):
  shape=tuple(z[f'shape_{name}']);masks=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(masks)==len(q)==len(boxes)==len(cls)==r['counts'][name] and np.all(q>=.25) and np.isfinite(boxes).all();order=sorted(range(len(q)),key=lambda i:(-float(q[i]),i));assert order==z[f'order_{name}'].tolist();items=[{'id':f'{name}:{i}','mask':masks[i]} for i in order];assert [x['id'] for x in items]==r['rankings'][name]
  for n in (5,10,30,'all'):
   arr=stack(items if n=='all' else items[:n]);out=r['scores'][name][str(n)];expected={tag:{str(t):match(refs[ix],[ids[j] for j in ix],arr,t) for t in (.5,.75)} for tag,ix in subsets.items()};assert expected==out['subsets'];hidden_ids={ids[j] for j in hidden};assert out['hidden_in_joint_assignment']=={str(t):sum(a['annotation_id'] in hidden_ids for a in expected['all'][str(t)]['assignments']) for t in (.5,.75)}
print('Verified 28 training image/label hashes, source polygon rasterization, 14 hidden identities, three model weight hashes, saved predictions, all subset and joint scores. Neural inference was not repeated; matching helper shared.')
