"""Measure label-free translation checks on real scan crops and toy controls."""
import hashlib,json,sys,time
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r59';sys.path.insert(0,str(ROOT/'diatom_pilot'))
from registration_consistency import compare_registration
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def warp(image,dx,dy):
 h,w=image.shape;return cv2.warpAffine(image,np.float32([[1,0,dx],[0,1,dy]]),(w,h),flags=cv2.INTER_NEAREST,borderMode=cv2.BORDER_REFLECT_101)
def overlay(a,b):return Image.fromarray(np.stack([a,b,b],axis=2))
def control_cases(planes,seed):
 ref=planes[1];h,w=ref.shape;dx,dy=7,-5;target=warp(ref,dx,dy);yield 'rigid',ref,target,{'type':'known_global','shift':[dx,dy]}
 target=warp(cv2.GaussianBlur(ref,(0,0),2.5),dx,dy);yield 'blurred_rigid',ref,target,{'type':'known_global','shift':[dx,dy]}
 left=warp(ref,dx,dy);right=warp(ref,dx+8,dy);target=np.concatenate((left[:,:w//2],right[:,w//2:]),axis=1);yield 'piecewise',ref,target,{'type':'no_single_global','left_shift':[dx,dy],'right_shift':[dx+8,dy]}
 rng=np.random.default_rng(seed);a=np.clip(128+rng.integers(-1,2,(h,w)),0,255).astype('uint8');b=np.clip(128+rng.integers(-1,2,(h,w)),0,255).astype('uint8');yield 'independent_noise',a,warp(b,dx,dy),{'type':'no_correspondence'}
 pat=np.rint(128+30*np.cos(2*np.pi*np.arange(16)/16)).astype('uint8');a=np.tile(pat,(h,(w+15)//16))[:,:w].copy();b=np.roll(a,16,axis=1);yield 'periodic_alias',a,b,{'type':'inherently_ambiguous','injected_roll':[16,0],'period_px':16}
 a=np.full((h,w),128,dtype='uint8');yield 'constant',a,a.copy(),{'type':'no_correspondence'}
 yield 'real_focus_pair',planes[0],planes[2],{'type':'unknown_real_shift','source_planes':[1,3]}
def main():
 p=json.loads((OUT/'protocol.json').read_text());meta=json.loads((OUT/'crops.json').read_text())
 for key,v in p['inputs'].items():
  if sha(Path(v['file']))!=v['sha256']:raise ValueError('Frozen input mismatch '+key)
 if (OUT/'results.json').exists():raise FileExistsError('Preserve results')
 records=[];started=time.monotonic()
 with np.load(OUT/'crops.npz',allow_pickle=False) as f:
  for i,field in enumerate(meta['fields'],1):
   planes=f[f'field_{i}']
   if planes.shape!=(3,768,768) or any(hashlib.sha256(planes[z].tobytes()).hexdigest()!=field['plane_sha256'][z] for z in range(3)):raise ValueError('Plane hash changed')
   for kind,reference,target,truth in control_cases(planes,20261215+i):
    a=time.monotonic();result=compare_registration(reference,target,local_limit=3.,cycle_limit=1.);seconds=time.monotonic()-a;methods={}
    for name in ('raw','centered','strict'):
     x=result[name];estimate=x['estimate'];item={'status':x['status'],'estimate':estimate}
     if truth['type']=='known_global' and estimate is not None:item['known_shift_error_px']=float(np.hypot(estimate['dx']-truth['shift'][0],estimate['dy']-truth['shift'][1]))
     if name=='strict':item.update(cycle_error=x['cycle_error'],max_local_disagreement=x['max_local_disagreement'],local=x['local'])
     methods[name]=item
    n=len(records)+1;np.savez_compressed(OUT/f'case-{n:02d}.npz',reference=reference,target=target);records.append({'field':i,'split':field['split'],'slide':field['slide'],'condition':kind,'truth':truth,'methods':methods,'elapsed_all_methods_seconds':seconds,'archive':f'case-{n:02d}.npz'});panel=Image.new('RGB',(1440,410),'#f3f6ef');draw=ImageDraw.Draw(panel)
    for col,name in enumerate(('reference','unregistered','raw','strict')):
     if name=='reference':im=Image.fromarray(reference).convert('RGB');title='Reference'
     elif name=='unregistered':im=overlay(reference,target);title='Unregistered overlay'
     else:
      v=methods[name];est=v['estimate'];use=v['status']=='tentative' and est is not None;aligned=warp(target,-est['dx'],-est['dy']) if use else target;im=overlay(reference,aligned);title=f'{name}: {v["status"]}'
     im.thumbnail((344,344));panel.paste(im,(col*360+8,45));draw.text((col*360+8,8),title,fill='#203a38')
    panel.save(OUT/f'case-{n:02d}.jpg',quality=86)
   print(f'{i}/6 {field["split"]} field controls complete',flush=True)
 (OUT/'results.json').write_text(json.dumps({'format':'r59-registration-controls-v1','protocol_sha256':sha(OUT/'protocol.json'),'records':records,'seconds':time.monotonic()-started,'warning':'Different scan filenames do not establish biological independence. Known shifts are synthetic; repeating patterns and independent noise have no uniquely identifiable shift. Real focus pairs have no motion ground truth. No segmentation or Academy accuracy measured.'},indent=2)+'\n');print('Registration control comparison complete.',flush=True)
if __name__=='__main__':main()
