"""Check fixed training sources, pixels, training references, prompts and checkpoint."""
import json,hashlib,zipfile
from pathlib import Path
import numpy as np
from PIL import Image
from l75_run import extract,paste
from l78_train import choose
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();p=json.loads((O/'protocol.json').read_text());sel=json.loads((O/'training-selection.json').read_text());manifest=json.loads((O/'training-image-manifest.json').read_text())['records'];scenes=json.loads((O/'training-scenes.json').read_text());run=json.loads((O/'training-run.json').read_text());pr=json.loads((O/'training-prompts.json').read_text());assert sha(O/'training-selection.json')==p['training_selection_sha256'] and sha(O/'training-image-manifest.json')==p['training_images_sha256'] and sha(O/'source-audit.json')==p['source_screen_sha256'] and sha(O/'protocol.json')==scenes['protocol_sha256']==run['protocol_sha256'] and sha(O/'training-scenes.json')==run['training_scenes_sha256'] and sha(O/'training-prompts.json')==run['prompts_sha256'] and sha(R/run['checkpoint'])==run['checkpoint_sha256'];ev=json.loads((R/'results/l75/protocol.json').read_text())['sources'];assert not ({v['sha256'] for v in manifest}&{v['image_sha256'] for v in ev});objects=[]
with zipfile.ZipFile(D/'source.zip') as z:
 for a,b in zip(sel['training_sources'],manifest):
  assert sha(R/b['path'])==b['sha256']==hashlib.sha256(z.read(b['source_member'])).hexdigest();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))
expected=[]
for row in scenes['records']:
 i=row['pair']-1;condition=row['condition'];bg=sel['backgrounds'][i];assert sha(R/bg['path'])==bg['sha256'] and (R/'scans'/bg['slide']).stat().st_size==bg['slide_bytes']>=1_000_000_000;canvas=np.asarray(Image.open(R/bg['path']).convert('RGB').resize((512,512),Image.Resampling.LANCZOS)).copy();(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];f0=paste(canvas,c0,m0,centers[0]);f1=paste(canvas,c1,m1,centers[1]);ref=np.stack([f0&~f1,f1]);z=np.load(O/row['archive']);assert sha(O/row['archive'])==row['archive_sha256'] and sha(O/row['image'])==row['image_sha256'] and np.array_equal(np.asarray(Image.open(O/row['image'])),canvas) and np.array_equal(z['visible'],ref) and np.array_equal(z['full_in_frame'],np.stack([f0,f1]));assert [i for i,x in enumerate(ref) if int(x.sum())>=50]==row['eligible_targets']
 for target in row['eligible_targets']:
  pos=choose(ref[target]);expected.append({'scene':row['image'],'source_target':target,'kind':'positive','points':[list(pos)],'labels':[1]})
  if condition=='crossing' and (1-target) in row['eligible_targets']:
   neg=choose(ref[1-target]);assert not ref[target][neg[1],neg[0]];expected.append({'scene':row['image'],'source_target':target,'kind':'positive_and_neighbor_negative','points':[list(pos),list(neg)],'labels':[1,0]})
assert expected==pr['prompts'] and len(expected)==run['examples'];print('Verified 16 source members, 8 background hashes, 24 reconstructed training scenes, all training point prompts and decoder checkpoint hash; did not rerun optimization.')
