"""Replay saved reference, point-mask filtering, NMS and matched scores."""
import json,hashlib
from pathlib import Path
import numpy as np
from diatom_pilot.fast_mask_nms import greedy_mask_nms
from l70_cellpose import match
from l72_run import spatial
R=Path(__file__).resolve().parents[1];O=R/'results/l78';S=R/'results/r79';CP=R/'results/r78';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();d=json.loads((O/'menne-results.json').read_text());p=json.loads((O/'menne-protocol.json').read_text());assert d['protocol_sha256']==sha(O/'menne-protocol.json') and sha(R/p['adapted_checkpoint'])==p['adapted_sha256'] and sha(R/p['baseline_reproduction'])==p['baseline_reproduction_sha256'] and sha(R/p['reference_records'])==p['reference_records_sha256'] and len(d['records'])==18
for r in d['records']:
 assert sha(R/'datasets/l78-menne/images'/f"{r['image_id']}.tif")==r['source_image_sha256'] and sha(S/r['source_sam_archive'])==r['source_sam_archive_sha256'] and sha(CP/r['source_reference_archive'])==r['source_reference_archive_sha256'] and sha(O/r['adapted_archive'])==r['adapted_archive_sha256'];a=np.load(S/r['source_sam_archive']);b=np.load(O/r['adapted_archive']);refs=np.load(CP/r['source_reference_archive'])['refs_visible'];refids=list(range(len(refs)));raw=np.unpackbits(a['mask_bits'])[:int(np.prod(a['mask_shape']))].reshape(a['mask_shape']).astype(bool);base=raw[int(a['detector_count']):];adapted=np.unpackbits(b['mask_bits'])[:int(np.prod(b['mask_shape']))].reshape(b['mask_shape']).astype(bool);ids=a['ids'][int(a['detector_count']):].tolist();assert ids==b['ids'].tolist() and np.array_equal(a['points'],b['points']) and len(ids)==64
 for name,mm,qq in [('baseline',base,a['quality']),('adapted',adapted,b['quality'])]:
  raw=[{'id':str(k),'mask':m,'quality':float(q),'eligible':300<=int(m.sum())<=50000 and float(q)>=.6} for k,m,q in zip(ids,mm,qq)];eligible=sorted((v for v in raw if v['eligible']),key=lambda x:-x['quality']);kept,aliases=greedy_mask_nms(eligible,.8);res=r['results'][name];assert len(eligible)==res['eligible_count'] and len(kept)==res['kept_count'] and aliases==res['aliases'];tmp=spatial([dict(x,id=x['id'][3:]) for x in kept],2);lookup={x['id'][3:]:x for x in kept};ranks={'quality':kept,'spatial2':[lookup[x['id']] for x in tmp]}
  for method,rank in ranks.items():
   assert [x['id'] for x in rank]==res['rankings'][method]
   for n in ('10','30','all'):
    chosen=rank if n=='all' else rank[:int(n)];arr=np.stack([x['mask'] for x in chosen]) if chosen else np.zeros((0,512,512),bool)
    for th in (.5,.75):assert match(refs,refids,arr,th)==res['scores'][method][n][str(th)]
  for th in (.5,.75):assert match(refs,refids,mm,th)['matched']==res['raw_oracle'][str(th)]
print('Verified 18 Menne source image, reference and model archives, 64 shared points, eligibility, NMS, ranks and source-region scores; inference was not rerun.')
