"""Validate all sparse weak-support files and reconstruct selected scenes."""
import collections,json
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset
from r112_scaleup_separated_render import render,sha
R=Path(__file__).resolve().parents[1];O=R/'results/r112/scaleup-separated-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_separated_render.py')
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h,f
data=UDEScaleupDataset('training',include_unverified_masks=True);assert len(p['scenes'])==len(m['records'])==192;used=[];names=collections.Counter();counts=collections.Counter();replay={0,1,64,95,191};cache={}
for i,(scene,row) in enumerate(zip(p['scenes'],m['records'])):
 assert scene['id']==row['id'] and scene['background']==row['background'] and len(row['instances'])==1+i%3;ip=O/row['image'];mp=O/row['mask_archive'];assert sha(ip)==row['image_sha256'] and sha(mp)==row['mask_archive_sha256'];im=np.asarray(Image.open(ip));assert im.shape==(768,768) and im.dtype==np.uint8
 with np.load(mp,allow_pickle=False) as z:
  n=len(row['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)
 assert all(not (ms[a]&ms[b]).any() for a in range(n) for b in range(a+1,n)) and row['support_overlap_pairs']==0;bgpath=R/row['background']['path'];assert sha(bgpath)==row['background']['sha256'];bg=np.asarray(Image.open(bgpath).convert('L'));assert int(np.count_nonzero(im!=bg))==row['changed_pixels_vs_background'] and not np.any((im!=bg)&~ms.any(axis=0));counts['scene_count_'+str(n)]+=1
 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=data.entries[idx];assert a['annotation_id']==entry['annotation_id'] and a['source_name']==entry['source_species'];used.append(idx);names[a['source_name']]+=1;full=b['transformed_support_pixels'];area=int(ms[j].sum());assert area==b['in_frame_support_pixels'] and full>0 and area>=.15*full and b['in_frame_fraction']==area/full;assert not a['prefer_edge'] or b['center_xy'][0] in (0,767);counts['partial_support']+=area<full;counts['instances']+=1
 if i in replay:
  image,supports,items,_,placement=render(scene,data,cache);assert np.array_equal(image,im) and np.array_equal(supports,ms) and items==row['instances'] and placement==row['placement']
assert len(used)==len(set(used))==384 and len(names)==80 and set(names.values())=={4,5};counts['scenes']=len(m['records']);counts['source_names']=len(names);counts['overlap_pairs']=0;report={'format':'r112-scaleup-separated-verify-v1','manifest_sha256':sha(O/'manifest.json'),'protocol_sha256':sha(O/'protocol.json'),'counts':dict(counts),'replayed_scene_indices':sorted(replay),'checks':'Every image and archive hash, 384 unique training source memberships, 80-name balance, projected support areas and zero pairwise support intersections verified; unknown background flags and unchanged pixels outside inserted supports checked. Five scenes reconstructed exactly. Overlap with unlabeled background organisms, mask correctness, biological visibility and realism are not tested; no tuning/check image pixels read.'};(O/'verify.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
