"""Reconstruct R75 composites from its frozen R41 inputs, without displaying RGB."""
import hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image
import r41_consensus_fresh_sources as exp
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r77';SCENES=Path('/tmp/diatom-r77-scenes')
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 prior=json.loads((ROOT/'results/r75/protocol.json').read_text())
 for x in prior['inputs']:
  if sha(x['path'])!=x['sha256']:raise ValueError('R75 input changed: '+x['path'])
 selection=json.loads(exp.SOURCE.read_text())['selection'];objects=[exp.extract21(selection[i-1],i) for i in exp.INDICES];source_protocol=json.loads((exp.OUT/'protocol.json').read_text());assert [x[2] for x in objects]==source_protocol['source_objects'];backgrounds=[np.asarray(Image.open(p).convert('RGB').crop((128,128,640,640))).copy() for p in (exp.BACKGROUND,exp.ALT)];old=json.loads((ROOT/'results/r75/results.json').read_text());records=[]
 for row in old['records']:
  pair=row['pair']-1;variant=row['variant'];crop1,mask1,_=objects[pair*2];crop2,mask2,_=objects[pair*2+1]
  if variant=='alternate':crop2=np.rot90(crop2).copy();mask2=np.rot90(mask2).copy()
  image=backgrounds[variant=='alternate'].copy();f1=np.zeros((512,512),bool);f2=np.zeros_like(f1);exp.base.paste(image,f1,crop1,mask1,256,256);exp.base.paste(image,f2,crop2,mask2,256,256);a=np.load(ROOT/'results/r75'/row['archive'],allow_pickle=False);assert sha(ROOT/'results/r75'/row['archive'])==row['archive_sha256'];assert np.array_equal(a['refs_full'],[f1,f2]) and np.array_equal(a['refs_visible'],[f1&~f2,f2]);path=SCENES/f'{variant}-{pair+1}.png';Image.fromarray(image).save(path);records.append({'variant':variant,'pair':pair+1,'rgb_path':str(path),'rgb_sha256':sha(path),'rgb_pixels_sha256':hashlib.sha256(image.tobytes()).hexdigest(),'archive':row['archive'],'archive_sha256':row['archive_sha256']});print(variant,pair+1,'references match',flush=True)
 (OUT/'scene-manifest.json').write_text(json.dumps({'format':'r77-reconstructed-scenes-v1','r75_protocol_sha256':sha(ROOT/'results/r75/protocol.json'),'script_sha256':sha(Path(__file__)),'records':records,'limitation':'R75 did not record RGB image hashes during original inference. Reconstruction uses matching frozen code/input hashes and verified target masks, but cannot directly prove exact original inference RGB bytes. Source RGB remains in temporary storage.'},indent=2)+'\n')
if __name__=='__main__':main()
