"""Validate prototype files, per-instance opaque visibility and source provenance."""
import hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/prototype';p=json.loads((O/'manifest.json').read_text())
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
assert p['generator_sha256']==sha(R/'research/r112_prototype.py') and p['selection_sha256']==sha(R/'results/l78/training-selection.json') and p['image_manifest_sha256']==sha(R/'results/l78/training-image-manifest.json');instances=0;empty=0;visible=0
for row in p['scenes']:
 ip=O/row['image'];ap=O/row['masks'];assert sha(ip)==row['image_sha256'] and sha(ap)==row['masks_sha256'] and Image.open(ip).size==(512,512);bg=row['background'];assert sha(R/bg['path'])==bg['sha256'];z=np.load(ap);full=z['full_in_frame'];vis=z['visible_opaque'];assert full.shape==vis.shape==(len(row['instances']),512,512) and str(z['background_label_status'])=='unknown'
 for i,item in enumerate(row['instances']):
  source=item['source'];assert sha(R/source['image_path'])==source['image_sha256'] and sha(R/source['annotation_path'])==source['annotation_sha256'];later=np.logical_or.reduce(full[i+1:]) if i+1<len(full) else np.zeros_like(full[i]);assert np.array_equal(vis[i],full[i]&~later);assert int(full[i].sum())==item['in_frame_pixels'] and int(vis[i].sum())==item['visible_pixels'];assert bool(vis[i].sum()>=50)==item['eligible_visible_at_least_50_pixels'];instances+=1;empty+=int(not full[i].any());visible+=int(item['eligible_visible_at_least_50_pixels'])
print(json.dumps({'scenes':len(p['scenes']),'instances':instances,'in_frame_empty':empty,'at_least_50_visible_pixels':visible,'check':'hashes, source references, dimensions, per-instance opaque visibility and background unknown; did not rerender pixels or validate biological accuracy'},indent=2))
