"""Rebuild source references, point plans, saved rankings and one-to-one scores."""
import json
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.fast_mask_nms import greedy_mask_nms
from l70_cellpose import match
from l86_oracle import sha
from l89_texture import variance_points
from r97_replay import padresize
from r99_compete import stack
R=Path(__file__).resolve().parents[1];O=R/'results/r106';D=R/'datasets/r80-gunduz';p=json.loads((O/'protocol.json').read_text());d=json.loads((O/'results.json').read_text());scr=json.loads((O/'screen-check.json').read_text());assert sha(O/'protocol.json')==d['protocol_sha256']==scr['protocol_sha256'] and sha(O/'screen-check.json')==d['screen_sha256'] and sha(R/'research/r106_replay.py')==d['script_sha256'] and sha('/tmp/mobile_sam.pt')==d['checkpoint_sha256']
for f,h in p['inputs'].items():assert sha(R/f)==h
old=json.loads((R/'results/r97/results.json').read_text())['records'];hist={v['id']:v for v in json.loads((R/'results/r80/results.json').read_text())['records']};assert len(old)==len(d['records'])==23 and len(scr['records'])==13
for r,prior in zip(d['records'],old):
 ident=r['id'];assert ident==prior['id'] and sha(R/r['source'])==r['source_sha256']==prior['source_image_sha256'] and sha(D/'masks'/f'{ident}.png')==r['source_mask_sha256']==prior['source_mask_sha256'] and sha(D/'xml'/f'{ident}.xml')==r['source_xml_sha256']==prior['source_xml_sha256'] and sha(R/'results/r97'/r['r97_archive'])==r['r97_archive_sha256']==prior['archive_sha256'] and sha(O/r['archive'])==r['archive_sha256'] and sha(O/r['panel'])==r['panel_sha256'];rgb=np.zeros((512,512,3),np.uint8);rgb[64:448]=np.asarray(Image.open(R/r['source']).convert('RGB').resize((512,384),Image.Resampling.LANCZOS));z=np.load(O/r['archive']);previous=np.load(R/'results/r97'/r['r97_archive']);refs=previous['refs'];ids=previous['ids'].tolist();assert np.array_equal(refs,z['refs']) and ids==z['refids'].tolist() and len(refs)==r['references'];edge=[]
 for ref in refs:
  yy,xx=np.nonzero(ref);edge.append(bool(xx.min()<=4 or xx.max()>=507 or yy.min()<=68 or yy.max()>=443))
 subsets={'all':list(range(len(refs))),'near_content_edge':[i for i,x in enumerate(edge) if x]};assert subsets==r['subsets'];h=hist[ident];sa=R/'results/r80'/h['sam_archive'];cp=R/'results/r80'/h['cellpose_archive'];assert sha(sa)==h['sam_archive_sha256']==r['historical_sam_sha256'] and sha(cp)==h['cellpose_archive_sha256']==r['historical_cp_sha256'];zz=np.load(sa);shape=tuple(zz['mask_shape']);m=np.unpackbits(zz['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);lookup=dict(zip(zz['ids'].tolist(),m));labels=np.load(cp)['labels'];historical=[]
 for name in h['rankings']['sam_first']:
  typ,sub=name.split(':',1);historical.append({'id':name,'mask':padresize(lookup[sub] if typ=='sam' else labels==int(sub))})
 shape=tuple(z['mask_shape']);m=np.unpackbits(z['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);q=z['quality'];assert len(m)==len(q)==256;raw=[];i=0
 for ty,y in enumerate((0,85,171,256)):
  for tx,x in enumerate((0,85,171,256)):
   pts=variance_points(rgb[y:y+256,x:x+256])
   for j,(px,py,var) in enumerate(pts):
    assert [x,y,x+256,y+256]==z['crops'][i].tolist() and [x+px,y+py]==z['points'][i].tolist() and var==z['variance'][i] and z['ids'][i]==f't{ty*4+tx}-q{j:02d}';sm=m[i][y:y+256,x:x+256];outside=m[i].copy();outside[y:y+256,x:x+256]=False;assert not outside.any();eligible=300<=int(m[i].sum())<=50000 and float(q[i])>=.6;edge=bool(sm[0].any() or sm[-1].any() or sm[:,0].any() or sm[:,-1].any());assert eligible==z['eligible'][i] and edge==z['edge'][i];raw.append({'id':str(z['ids'][i]),'mask':m[i],'quality':float(q[i]),'eligible':eligible,'edge':edge,'point':[x+px,y+py]});i+=1
 eligible=sorted((x for x in raw if x['eligible']),key=lambda v:-v['quality']);kept,aliases=greedy_mask_nms(eligible,.8);valid=[v for v in eligible if 64<=v['point'][1]<448];pad=[v for v in eligible if not 64<=v['point'][1]<448];vk,va=greedy_mask_nms(valid,.8);vkids={v['id'] for v in vk};deferred=[v for v in kept if 64<=v['point'][1]<448]+[v for v in kept if not 64<=v['point'][1]<448];vf=vk+[v for v in valid if v['id'] not in vkids]+pad;assert len(vf)==len(eligible) and {v['id'] for v in vf}=={v['id'] for v in eligible} and aliases==r['aliases'] and va==r['valid_aliases'] and len(eligible)==r['eligible_count'] and len(kept)==r['original_kept'] and sum(v['edge'] for v in kept)==r['edge_kept'] and sum(not 64<=v['point'][1]<448 for v in raw)==r['raw_padding'];streams={'original':kept,'defer_padding':deferred,'valid_first':vf,'historical':historical}
 for name,items in streams.items():
  assert [v['id'] for v in items]==r['rankings'][name]
  for n in (10,30,60,'all'):
   chosen=items if n=='all' else items[:n];stats={'masks':len(chosen),'padding_points':None if name=='historical' else sum(not 64<=v['point'][1]<448 for v in chosen)};assert stats==r['display_counts'][name][str(n)]
   for tag,ix in subsets.items():
    for t in (.5,.75):assert match(refs[ix],[ids[i] for i in ix],stack(chosen),t)==r['scores'][name][str(n)][tag][str(t)]
 for name,items in [('raw',raw),('eligible',eligible)]:
  for t in (.5,.75):assert match(refs,ids,stack(items),t)==r['stage_scores'][name][str(t)]
 print(ident,'verified',flush=True)
print('Verified source/reference and model archive hashes, shared point selector and NMS, padding policies, historical ranks, display budgets and all scores; no inference rerun.')
