"""Check every new scene and source restriction; rerender selected fields."""
import collections,json
from pathlib import Path
import numpy as np
from PIL import Image
from r112_breadth_scenes_render import BreadthAdapter,render,sha
R=Path(__file__).resolve().parents[1];O=R/'results/r112/breadth-diverse-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_breadth_scenes_render.py')
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h,f
data=BreadthAdapter();assert len(data)==784 and len(m['records'])==len(p['scenes'])==98;used=[];names=set();genera=set();counts=collections.Counter();replay={0,1,2,49,97};cache={}
for i,(scene,row) in enumerate(zip(p['scenes'],m['records'])):
 assert scene['id']==row['id'] and scene['mode']==row['mode'] and scene['background']==row['background'];n=len(row['instances']);assert n==len(scene['instances']) and n in (2,4,6,8,10,12,14);ip=O/row['image'];mp=O/row['mask_archive'];assert sha(ip)==row['image_sha256'] and sha(mp)==row['mask_archive_sha256'];img=np.asarray(Image.open(ip));assert img.shape==(768,768) and img.dtype==np.uint8
 with np.load(mp,allow_pickle=False) as z:
  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==row['support_overlap_pairs'] and (row['mode']!='separated' or overlap==0);counts['overlap_pairs']+=overlap;counts['scenes_with_overlap']+=bool(overlap);counts['scene_mode_'+row['mode']]+=1;counts['instances_per_scene_'+str(n)]+=1
 bgpath=R/row['background']['path'];assert sha(bgpath)==row['background']['sha256'];bg=np.asarray(Image.open(bgpath).convert('L'));assert int(np.count_nonzero(img!=bg))==row['changed_pixels_vs_background'] and not np.any((img!=bg)&~ms.any(axis=0))
 for j,(a,b) in enumerate(zip(scene['instances'],row['instances'])):
  assert all(b[k]==v for k,v in a.items());idx=a['training_index'];entry,part=data.data.entries[idx];assert part=='training' and a['annotation_id']==entry['annotation_id'] and a['source_name']==entry['source_species'];used.append(idx);names.add(a['source_name']);genera.add(a['source_genus']);full=b['transformed_support_pixels'];area=int(ms[j].sum());assert area==b['in_frame_support_pixels'] and area<=full and b['in_frame_fraction']==(area/full if full else None);counts['partial_support']+=bool(full and 0<area<full);counts['empty_support']+=area==0
 if i in replay:
  out,masks,items,_,placement=render(scene,data,cache);assert np.array_equal(out,img) and np.array_equal(masks,ms) and items==row['instances'] and placement==row['placement']
assert sorted(used)==list(range(784)) and len(names)==137;counts['scenes']=98;counts['instances']=len(used);counts['source_name_strings']=len(names);counts['source_genera']=len(genera);report={'format':'r112-breadth-diverse-scenes-verify-v1','manifest_sha256':sha(O/'manifest.json'),'protocol_sha256':sha(O/'protocol.json'),'counts':dict(counts),'replayed_scene_indices':sorted(replay),'checks':'All image/support hashes, source memberships in prior training components, projected areas, overlap counts, unknown-background metadata and unchanged pixels outside support checked. Five scenes across placement modes reconstructed exactly. This does not verify mask anatomy, identify background organisms, source names, realistic optics or independent biological performance.'};(O/'verify.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
