"""Reconstruct tile placement, mask eligibility, NMS and all scores."""
import json
from pathlib import Path
import numpy as np
from diatom_pilot.fast_mask_nms import greedy_mask_nms
from l70_cellpose import match
from l86_oracle import sha
from r99_compete import stack
R=Path(__file__).resolve().parents[1];O=R/'results/l88';S=R/'results/l75';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/l88_tiles.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((S/'results.json').read_text())['records'];assert len(old)==len(d['records'])==16
for r,prior in zip(d['records'],old):
 assert (r['pair'],r['condition'],r['split'])==(prior['pair'],prior['condition'],prior['split']) and sha(S/r['source_image'])==r['source_image_sha256']==prior['image_sha256'] and sha(S/r['source_archive'])==r['source_archive_sha256']==prior['archive_sha256'] and sha(O/r['archive'])==r['archive_sha256'] and sha(O/r['panel'])==r['panel_sha256'];z=np.load(S/r['source_archive']);a=np.load(O/r['archive']);refs=z['refs_visible'];assert np.array_equal(refs,a['refs']);shape=tuple(a['mask_shape']);m=np.unpackbits(a['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);q=a['quality'];assert len(m)==len(q)==256==r['raw_count'];items=[];i=0
 for ty,y in enumerate((0,85,171,256)):
  for tx,x in enumerate((0,85,171,256)):
   for py in (32,96,160,224):
    for px in (32,96,160,224):
     mask=m[i];crop=[x,y,x+256,y+256];point=[x+px,y+py];assert crop==a['crops'][i].tolist() and point==a['points'][i].tolist();outside=mask.copy();outside[y:y+256,x:x+256]=False;assert not outside.any();small=mask[y:y+256,x:x+256];edge=bool(small[0].any() or small[-1].any() or small[:,0].any() or small[:,-1].any());eligible=300<=int(mask.sum())<=50000 and float(q[i])>=.6;ident=f't{ty*4+tx}-p{py:03d}-{px:03d}';assert ident==a['ids'][i] and edge==a['edge'][i] and eligible==a['eligible'][i];items.append({'id':ident,'mask':mask,'quality':float(q[i]),'eligible':eligible,'edge_contact':edge});i+=1
 eligible=sorted((x for x in items if x['eligible']),key=lambda x:-x['quality']);kept,aliases=greedy_mask_nms(eligible,.8);assert len(eligible)==r['eligible_count'] and len(kept)==r['kept_count'] and aliases==r['aliases'] and [x['id'] for x in kept]==r['ranking'] and sum(x['edge_contact'] for x in items)==r['edge_raw_count'] and sum(x['edge_contact'] for x in kept)==r['edge_kept_count'];ids=prior['included_visible_ids']
 for name,a1 in [('raw',items),('eligible',eligible)]:
  for t in (.5,.75):assert match(refs[ids],ids,stack(a1),t)==r['scores'][name][str(t)]
 for n in (10,30,60,'all'):
  for t in (.5,.75):assert match(refs[ids],ids,stack(kept if n=='all' else kept[:n]),t)==r['scores']['tiled'][str(n)][str(t)]
 print(r['pair'],r['condition'],'verified',flush=True)
print('Verified crop coordinates, mapped support bounds, source/archives, eligibility, shared NMS and matching; inference and crop-resizing not rerun.')
