"""Check every generated weak-support archive and replay selected scenes."""
import json
from collections import Counter
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset
from r112_scaleup_scene_render import render,sha
R=Path(__file__).resolve().parents[1];O=R/'results/r112/scaleup-crowded-scenes';p=json.loads((O/'protocol.json').read_text());m=json.loads((O/'manifest.json').read_text());assert m['protocol_sha256']==sha(O/'protocol.json') and m['script_sha256']==sha(R/'research/r112_scaleup_scene_render.py')
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h,f
dataset=UDEScaleupDataset('training',include_unverified_masks=True);assert len(p['scenes'])==len(m['records'])==283;used=[];counts=Counter();species=set();genera=set();replay={0,1,93,141,282};cache={}
for i,(scene,r) in enumerate(zip(p['scenes'],m['records'])):
 assert scene['id']==r['id'] and scene['background']==r['background'] and len(scene['instances'])==len(r['instances']) and len(r['instances']) in (4,6,8,10,12,14,16);ip=O/r['image'];mp=O/r['mask_archive'];assert sha(ip)==r['image_sha256'] and sha(mp)==r['mask_archive_sha256'];im=np.asarray(Image.open(ip));assert im.shape==(768,768) and im.dtype==np.uint8;z=np.load(mp,allow_pickle=False);n=len(r['instances']);assert tuple(z['support_shape'])==(n,768,768) and str(z['background_label_status'])=='unknown' and str(z['visible_support_status'])=='undefined';ms=np.unpackbits(z['support_bits'],count=n*768*768).reshape(n,768,768).astype(bool)
 overlap=sum(bool((ms[a]&ms[b]).any()) for a in range(n) for b in range(a+1,n));assert overlap==r['support_overlap_pairs'];counts['scenes_with_overlap']+=bool(overlap);counts['overlap_pairs']+=overlap
 path=R/r['background']['path'];assert sha(path)==r['background']['sha256'];bg=np.asarray(Image.open(path).convert('L'));assert int(np.count_nonzero(im!=bg))==r['changed_pixels_vs_background'];assert not np.any((im!=bg)&~ms.any(axis=0))
 for j,(a,b) in enumerate(zip(scene['instances'],r['instances'])):
  assert all(b[k]==v for k,v in a.items());idx=a['training_index'];entry=dataset.entries[idx];assert a['annotation_id']==entry['annotation_id'] and a['source_name']==entry['source_species'];used.append(idx);species.add(a['source_name']);genera.add(a['source_genus']);area=int(ms[j].sum());assert area==b['in_frame_support_pixels'] and area<=b['transformed_support_pixels'];full=b['transformed_support_pixels'];assert b['in_frame_fraction']==(area/full if full else None);counts['instances']+=1;counts['empty_support']+=area==0;counts['partial_support']+=0<area<full;counts['complete_support']+=full>0 and area==full
 if i in replay:
  out,supports,items,_=render(scene,dataset,cache);assert np.array_equal(out,im) and np.array_equal(supports,ms) and items==r['instances']
assert sorted(used)==list(range(2830));counts['source_names']=len(species);counts['source_genera']=len(genera);counts['scenes']=len(m['records']);report={'format':'r112-scaleup-crowded-verify-v1','manifest_sha256':sha(O/'manifest.json'),'protocol_sha256':sha(O/'protocol.json'),'counts':dict(counts),'replayed_scene_indices':sorted(replay),'checks':'All scene and mask-file hashes, grayscale shape, 2830 unique training source memberships, per-support area, overlap counts, background unknown flags and unchanged pixels outside all supports checked. Five scenes reconstructed exactly from sources, masks and backgrounds. Other source pixels and all scene renderings not replayed. These are projected model proposals, not verified segmentation, real-world visibility or Academy accuracy; no tuning/check pixels were read.'};(O/'verify.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
