"""Verify source data, preserved raw masks and replayed focal-control scores."""
import hashlib,json
from pathlib import Path
import numpy as np
import r38_synthetic_crossings as base
import r58_focal_controls as control
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r58'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 data=json.loads((OUT/'results.json').read_text());info=json.loads((OUT/'backgrounds.json').read_text());manifest=json.loads((OUT/'source-objects/manifest.json').read_text());total=0
 if sha(OUT/'backgrounds.npz')!=info['npz_sha256']:raise ValueError('Background archive changed')
 for r in manifest['records']:
  for kind in ('image','mask'):
   if sha(OUT/'source-objects'/f"{r['id']}-{kind}.png")!=r[kind+'_sha256']:raise ValueError('Source changed')
 with np.load(OUT/'backgrounds.npz',allow_pickle=False) as f:
  for i,r in enumerate(info['fields'],1):
   a=f[f'field_{i}']
   if a.shape!=(5,768,768) or any(hashlib.sha256(a[z].tobytes()).hexdigest()!=r['plane_sha256'][z] for z in range(5)):raise ValueError('Plane crop changed')
 for r in data['records']:
  with np.load(OUT/r['archive'],allow_pickle=False) as f:
   n,h,w=map(int,f['candidate_shape']);ids=f['candidate_ids'].tolist();zs=f['candidate_z'].tolist();bits=np.unpackbits(f['candidate_bits'])
   if (h,w)!=(512,512) or f['planes'].shape!=(5,512,512) or len(ids)!=n or len(set(ids))!=n or len(zs)!=n or len(bits)<n*h*w:raise ValueError('Malformed archive')
   masks=bits[:n*h*w].reshape(n,h,w).astype(bool);refs=f['full_masks'];raw=[{'id':ident,'z':z,'mask':m} for ident,z,m in zip(ids,zs,masks)];pool,aliases=control.nms(raw,.8)
   if aliases!=r['suppression_aliases_08'] or len(pool)!=r['scores']['pool08']['candidates']:raise ValueError('Suppression differs')
   if len(refs):
    if base.assign(refs,[c['mask'] for c in pool[:20]],.5)!=r['scores']['pool08']['top20']:raise ValueError('Matching differs')
    overlap=int(np.count_nonzero(refs[0]&refs[1]))
    if overlap!=r['overlap_pixels'] or (r['condition'].startswith('crossing') and overlap==0) or (r['condition']=='separated_split' and overlap!=0):raise ValueError('Control geometry mismatch')
   elif r['condition']!='background_only':raise ValueError('Missing targets')
   total+=n
 print(f'Verified {len(data["records"])} control scenes, {total} preserved raw masks, reference scores, sources and background crops.')
if __name__=='__main__':main()
