"""Reconstruct real field pixels, tile prompt coordinates, filtering and 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 r99_compete import stack
R=Path(__file__).resolve().parents[1];O=R/'results/r105';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/r105_real.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/r98/results.json').read_text())['records'];prior=json.loads((R/'results/r87/results.json').read_text())['records'];assert len(old)==len(d['records'])==13
for r,orig in zip(d['records'],old):
 assert r['index']==orig['index'] and sha(R/r['source'])==r['source_sha256']==orig['source_sha256'] and sha(R/r['reference_archive'])==r['reference_archive_sha256']==orig['prior_archive_sha256'] and sha(O/r['archive'])==r['archive_sha256'] and sha(O/r['panel'])==r['panel_sha256'];im=Image.open(R/r['source']).convert('RGB');rgb=np.zeros((512,512,3),np.uint8);rgb[64:448]=np.asarray(im.resize((512,384),Image.Resampling.LANCZOS));z=np.load(O/r['archive']);oldz=np.load(R/r['reference_archive']);refs=oldz['refs'];ids=oldz['annotation_ids'].tolist();assert np.array_equal(z['refs'],refs) and z['ids'].tolist()==ids and len(refs)==r['references'];shape=tuple(oldz['mask_shape']);m=np.unpackbits(oldz['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);lookup=dict(zip(oldz['ids'].tolist(),m));rank=prior[r['index']]['policies']['256']['ranking'];assert rank==r['whole_ranking'];whole=[{'id':v,'mask':lookup[v]} for v in rank]
 for n in (10,30,60,'all'):
  for t in (.5,.75):assert match(refs,ids,stack(whole if n=='all' else whole[:n]),t)==r['scores']['whole']['ranked'][str(n)][str(t)]
 for method in ('uniform','variance'):
  shape=tuple(z[method+'_mask_shape']);m=np.unpackbits(z[method+'_mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);q=z[method+'_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=[(a,b,0.) for b in (32,96,160,224) for a in (32,96,160,224)] if method=='uniform' else 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[method+'_crops'][i].tolist() and [x+px,y+py]==z[method+'_points'][i].tolist() and var==z[method+'_variance'][i] and z[method+'_ids'][i]==f't{ty*4+tx}-q{j:02d}';small=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(small[0].any() or small[-1].any() or small[:,0].any() or small[:,-1].any());assert eligible==z[method+'_eligible'][i] and edge==z[method+'_edge'][i];raw.append({'id':str(z[method+'_ids'][i]),'mask':m[i],'quality':float(q[i]),'eligible':eligible,'edge':edge,'point':[x+px,y+py]});i+=1
  elig=sorted((x for x in raw if x['eligible']),key=lambda x:-x['quality']);kept,aliases=greedy_mask_nms(elig,.8);s=r['stats'][method];assert len(elig)==s['eligible'] and len(kept)==s['kept'] and aliases==s['aliases'] and [x['id'] for x in kept]==s['ranking'] and sum(x['edge'] for x in raw)==s['edge_raw'] and sum(x['edge'] for x in kept)==s['edge_kept'] and sum(bool(refs[:,v['point'][1],v['point'][0]].any()) for v in raw)==s['on_reference'] and sum(not 64<=v['point'][1]<448 for v in raw)==s['in_padding']
  for stage,items in [('raw',raw),('eligible',elig)]:
   for t in (.5,.75):assert match(refs,ids,stack(items),t)==r['scores'][method][stage][str(t)]
  for n in (10,30,60,'all'):
   for t in (.5,.75):assert match(refs,ids,stack(kept if n=='all' else kept[:n]),t)==r['scores'][method]['ranked'][str(n)][str(t)]
 print(r['index'],'verified',flush=True)
print('Verified source hashes, archived references, point selection, crop bounds, candidate counts, rankings, NMS and scores. Shared point selector, matcher and NMS; inference not rerun.')
