"""Check grayscale outputs and geometry against the original development prototype."""
import hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image
R=Path(__file__).resolve().parents[1];old=R/'results/r112/design/prototype';out=R/'results/r112/design/prototype-grayscale'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
a=json.loads((old/'manifest.json').read_text());b=json.loads((out/'manifest.json').read_text());assert b['generator_sha256']==sha(R/'research/r112_grayscale.py');assert b['seed']==a['seed'];n=0
for x,y in zip(a['scenes'],b['scenes']):
 assert x['id']==y['id'] and x['condition']==y['condition'] and x['instances']==y['instances'] and x['background']==y['background'];img=out/y['image'];assert sha(img)==y['image_sha256'] and Image.open(img).mode=='L' and Image.open(img).size==(512,512);p=np.load(old/x['masks']);q=np.load(out/y['masks']);assert sha(out/y['masks'])==y['masks_sha256']
 for k in ('full_in_frame','visible_opaque','background_label_status'):assert np.array_equal(p[k],q[k])
 for j in range(len(y['instances'])):
  full=q['full_in_frame'];later=np.logical_or.reduce(full[j+1:]) if j+1<len(full) else np.zeros_like(full[j]);assert np.array_equal(q['visible_opaque'][j],full[j]&~later);n+=1
assert len(a['scenes'])==len(b['scenes'])==24 and Image.open(out/'contact-sheet.jpg').mode=='L'
print(json.dumps({'scenes':len(b['scenes']),'instances':n,'scene_images_are_8bit_grayscale':True,'contact_sheet_is_grayscale':True,'all_instance_metadata_and_masks_match_original':True,'limits':'Checks saved data, not realism, biological correctness or rerendering.'},indent=2))
