"""Evaluate multiple correlation peaks on prior and new synthetic controls."""
import hashlib,json,math,time,sys
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l48';R59=ROOT/'results/r59';sys.path.insert(0,str(ROOT/'diatom_pilot'))
from phase_hypotheses import translation_hypotheses
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def rank_of(peaks,xy,tolerance=1.5):
 return next((i+1 for i,p in enumerate(peaks) if np.hypot(p['dx']-xy[0],p['dy']-xy[1])<=tolerance),None)
def generate_new():
 # Three new exact sheared-periodic patterns. Target can be produced by zero
 # translation or the stated whole-period roll; neither is uniquely correct.
 for n,(p,q) in enumerate(((12,16),(8,24),(16,24)),1):
  yy,xx=np.indices((768,768));a=np.rint(128+40*np.cos(2*np.pi*(xx+2*yy)/p)+40*np.cos(2*np.pi*(2*xx-yy)/q)).clip(0,255).astype('uint8');shift=math.lcm(p,q);b=np.roll(a,shift,axis=1)
  if not np.array_equal(a,b):raise ValueError('Pattern not exactly periodic')
  yield {'set':'new_synthetic','condition':'sheared_periodic','group':f'pattern-{n}','truth':{'type':'ambiguous','alternatives':[[0,0],[shift,0]]},'reference':a,'target':b}
 # Use actual previously inspected crops only as weak, nonperiodic texture in
 # a synthetic grating. Circular translation is known in this toy test.
 with np.load(R59/'crops.npz',allow_pickle=False) as f:
  for i in (4,5,6):
   image=f[f'field_{i}'][1].astype('float32');yy,xx=np.indices(image.shape);a=np.rint(128+25*np.cos(2*np.pi*(xx+yy)/24)+25*np.cos(2*np.pi*(2*xx-yy)/32)+.12*(image-image.mean())).clip(0,255).astype('uint8');b=np.roll(np.roll(a,-9,axis=0),13,axis=1)
   yield {'set':'new_synthetic','condition':'near_periodic','group':f'field-{i}','truth':{'type':'known_global','shift':[13,-9]},'reference':a,'target':b}
def main():
 p=json.loads((OUT/'protocol.json').read_text())
 for key,v in p['inputs'].items():
  if sha(Path(v['file']))!=v['sha256']:raise ValueError('Frozen input mismatch '+key)
 for name,h in p['prior_archives'].items():
  if sha(R59/name)!=h:raise ValueError('Input archive changed '+name)
 if (OUT/'results.json').exists():raise FileExistsError('Preserve existing results')
 cases=[];r59=json.loads((R59/'results.json').read_text())['records']
 for row in r59:
  # The one-dimensional periodic control is repeated identically for each
  # field; keep one and report it as one unique pattern.
  if row['condition']=='periodic_alias' and row['field']!=1:continue
  with np.load(R59/row['archive'],allow_pickle=False) as f:a=f['reference'].copy();b=f['target'].copy()
  truth=row['truth'].copy()
  if truth['type']=='inherently_ambiguous':truth={'type':'ambiguous','alternatives':[[0,0],truth['injected_roll']]}
  elif truth['type']=='no_single_global':truth={'type':'piecewise','alternatives':[truth['left_shift'],truth['right_shift']]}
  cases.append({'set':row['split'],'condition':row['condition'],'group':f'field-{row["field"]}','truth':truth,'reference':a,'target':b,'prior_archive':row['archive']})
 for i,row in enumerate(json.loads((R59/'periodic-generalization.json').read_text())['records'],1):
  with np.load(R59/row['archive'],allow_pickle=False) as f:a=f['reference'].copy();b=f['target'].copy()
  cases.append({'set':'inspected_periodic','condition':'periodic_2d','group':f'pattern-{i}','truth':{'type':'ambiguous','alternatives':[[0,0],row['injected_roll']]},'reference':a,'target':b,'prior_archive':row['archive']})
 cases.extend(generate_new());records=[]
 for i,case in enumerate(cases,1):
  a,b=case['reference'],case['target'];variants={};surfaces={}
  for window in ('none','hann'):
   t=time.monotonic();res=translation_hypotheses(a,b,max_shift=128,max_hypotheses=64,min_relative=.25,window=window,radius=3);elapsed=time.monotonic()-t;surfaces[window]=res.pop('surface');res['seconds']=elapsed;truth=case['truth'];alts=truth.get('alternatives',([truth['shift']] if 'shift' in truth else []));res['reference_ranks']=[rank_of(res['peaks'],x) for x in alts];variants[window]=res
  save={'surface_none':surfaces['none'],'surface_hann':surfaces['hann']}
  if case['set']=='new_synthetic':save.update(reference=a,target=b)
  name=f'case-{i:02d}.npz';np.savez_compressed(OUT/name,**save);row={k:v for k,v in case.items() if k not in ('reference','target')};row.update({'archive':name,'variants':variants});records.append(row)
  panel=Image.new('RGB',(1440,410),'#f3f6ef');draw=ImageDraw.Draw(panel);img=Image.fromarray(a).convert('RGB');img.thumbnail((344,344));panel.paste(img,(8,45));draw.text((8,8),'Reference',fill='#203a38');img=Image.fromarray(np.stack([a,b,b],axis=2)).convert('RGB');img.thumbnail((344,344));panel.paste(img,(368,45));draw.text((368,8),'Reference red / target cyan',fill='#203a38')
  for col,window in enumerate(('none','hann'),2):
   surface=surfaces[window];hi=float(surface.max());s=np.clip(surface/max(hi,1e-12),0,1);heat=cv2.applyColorMap((s*255).astype('uint8'),cv2.COLORMAP_TURBO)[:,:,::-1];img=Image.fromarray(heat).convert('RGB');mark=ImageDraw.Draw(img)
   for pk in variants[window]['peaks'][:10]:
    x,y=pk['dx']+128,pk['dy']+128;mark.ellipse((x-2,y-2,x+2,y+2),outline='white',width=1)
   img=img.resize((344,344),Image.Resampling.NEAREST);panel.paste(img,(col*360+8,45));draw.text((col*360+8,8),f'{window} peak surface, top 10',fill='#203a38')
  panel.save(OUT/f'case-{i:02d}.jpg',quality=86);print(f'{i}/{len(cases)} {case["condition"]} {case["group"]} processed',flush=True)
 (OUT/'results.json').write_text(json.dumps({'format':'l48-phase-hypotheses-v1','protocol_sha256':sha(OUT/'protocol.json'),'records':records,'warning':'Mostly previously inspected controls; new patterns are synthetic. Finite circular correlation peaks are uncalibrated; a missing peak or no ambiguity flag does not prove accuracy. Real focus pairs have unknown motion.'},indent=2)+'\n');print('Multiple-peak comparison complete.',flush=True)
if __name__=='__main__':main()
