"""Build predeclared point-training scenes; never consumes evaluation labels."""
import hashlib,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from l75_run import extract,paste
R=Path(__file__).resolve().parents[1];O=R/'results/l78';D=R/'datasets/r84-khanom';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 proto=json.loads((O/'protocol.json').read_text());assert sha(O/'training-selection.json')==proto['training_selection_sha256'] and sha(O/'training-image-manifest.json')==proto['training_images_sha256'] and sha(O/'source-audit.json')==proto['source_screen_sha256'];sel=json.loads((O/'training-selection.json').read_text());manifest=json.loads((O/'training-image-manifest.json').read_text())['records'];objects=[]
 for a,b in zip(sel['training_sources'],manifest):
  obj={'image_path':b['path'],'image_sha256':b['sha256'],'annotation_path':str(D/a['coco_file']),'annotation_sha256':a['coco_sha256'],'image_id':a['image_id'],'annotation_id':a['annotation_id']};objects.append(extract(obj))
 rows=[]
 for i in range(8):
  bg=sel['backgrounds'][i];assert sha(R/bg['path'])==bg['sha256'] and (R/'scans'/bg['slide']).stat().st_size==bg['slide_bytes'] and bg['slide_bytes']>=1_000_000_000;back=np.asarray(Image.open(R/bg['path']).convert('RGB').resize((512,512),Image.Resampling.LANCZOS));
  for condition in ('separated','crossing','partial'):
   (c0,m0),(c1,m1)=objects[2*i:2*i+2];c1=np.rot90(c1).copy() if condition=='crossing' else c1;m1=np.rot90(m1).copy() if condition=='crossing' else m1;centers={'separated':((140,256),(372,256)),'crossing':((256,256),(256,256)),'partial':((10,256),(375,256))}[condition];canvas=back.copy();f0=paste(canvas,c0,m0,centers[0]);f1=paste(canvas,c1,m1,centers[1]);visible=np.stack([f0&~f1,f1]);full=np.stack([f0,f1]);name=f'pair-{i+1}-{condition}';image=O/(name+'.png');archive=O/(name+'.npz');Image.fromarray(canvas).save(image);np.savez_compressed(archive,visible=visible,full_in_frame=full);rows.append({'pair':i+1,'condition':condition,'image':image.name,'image_sha256':sha(image),'archive':archive.name,'archive_sha256':sha(archive),'source_indices':[2*i,2*i+1],'visible_pixels':[int(x.sum()) for x in visible],'eligible_targets':[j for j,x in enumerate(visible) if int(x.sum())>=50]})
 (O/'training-scenes.json').write_text(json.dumps({'format':'l78-scenes-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':rows},indent=2)+'\n');print('prepared',len(rows),'scenes;',sum(len(x['eligible_targets']) for x in rows),'eligible source targets')
if __name__=='__main__':main()
