"""Replay frozen L66 prompt-selection policies against R75 source masks."""
import hashlib,json,time
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
from diatom_pilot.prompt_sampling import sample_64
from diatom_pilot.fast_mask_nms import greedy_mask_nms
import r38_synthetic_crossings as base
import r41_consensus_fresh_sources as r41
import l65_rank_candidates as evals
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r77';SRC=ROOT/'results/r75'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def panel(refs,ranks,path):
 im=Image.new('RGB',(1200,330),'white');draw=ImageDraw.Draw(im)
 for col,(name,masks) in enumerate([('Visible reference',refs),('Uniform: first ten',[x['mask'] for x in ranks['uniform'][:10]]),('Contrast: first ten',[x['mask'] for x in ranks['contrast'][:10]]),('Mixed: first ten',[x['mask'] for x in ranks['mixed'][:10]])]):
  tile=Image.new('RGBA',(512,512),'#eef3ee')
  for j,m in enumerate(masks):
   layer=Image.new('RGBA',(512,512),['#008a70','#cd603b','#7357b4','#c29d2a'][j%4]);layer.putalpha(Image.fromarray(m.astype('uint8')*100));tile=Image.alpha_composite(tile,layer)
  im.paste(tile.convert('RGB').resize((300,300)),(col*300,30));draw.text((300*col+4,7),name,fill='#203a38')
 im.save(path)
def main():
 p=json.loads((OUT/'protocol.json').read_text())
 for x in p['inputs']:
  if sha(x['path'])!=x['sha256']:raise ValueError('Changed input: '+x['path'])
 source=json.loads((SRC/'results.json').read_text());manifest=json.loads((OUT/'scene-manifest.json').read_text());records=[]
 for old,scene in zip(source['records'],manifest['records']):
  start=time.monotonic();assert (old['variant'],old['pair'])==(scene['variant'],scene['pair']);assert sha(scene['rgb_path'])==scene['rgb_sha256'] and sha(SRC/old['archive'])==old['archive_sha256'];image=np.asarray(Image.open(scene['rgb_path']).convert('RGB'));a=np.load(SRC/old['archive'],allow_pickle=False);shape=tuple(a['candidate_shape']);masks=np.unpackbits(a['candidate_bits'])[:int(np.prod(shape))].reshape(shape).astype(bool);ids=[str(x) for x in a['candidate_ids']];refs=list(a['refs_visible']);full=list(a['refs_full']);points=a['points'];gray=cv2.cvtColor(image,cv2.COLOR_RGB2GRAY);subsets,localstd=sample_64(gray,points);det=list(a['detector_masks']);policies={};ranks={}
  for method,indices in subsets.items():
   eligible=[{'id':ids[i],'mask':masks[i],'quality':float(a['quality'][i])} for i in indices if a['eligible'][i]];eligible=sorted(eligible,key=lambda x:-x['quality']);kept,aliases=greedy_mask_nms(eligible,.8)
   for c in kept:c['support']=max((base.iou(c['mask'],m) for m in det),default=0.)
   supported=sorted(kept,key=lambda c:(-(c['support']>=.25),-c['quality']));rank=r41.interleave(supported,kept);ranks[method]=rank;policies[method]={'prompt_indices':indices,'eligible_ids':[q['id'] for q in eligible],'aliases':aliases,'ranking':[q['id'] for q in rank],'budgets':{str(n):evals.score(refs,full,rank[:n]) for n in (5,10,20)},'all_kept':evals.score(refs,full,kept),'all_eligible':evals.score(refs,full,eligible)}
  name=f"{old['variant']}-{old['pair']}";pic=OUT/(name+'.png');panel(refs,ranks,pic);rec={'variant':old['variant'],'pair':old['pair'],'scene_rgb_path':scene['rgb_path'],'scene_rgb_sha256':scene['rgb_sha256'],'source_mask_archive':old['archive'],'source_mask_archive_sha256':old['archive_sha256'],'local_std':localstd.tolist(),'policies':policies,'image':pic.name,'image_sha256':sha(pic),'seconds':round(time.monotonic()-start,3)};records.append(rec);print(name,{k:(v['budgets']['10']['visible05']['matched'],v['budgets']['20']['visible05']['matched'],v['all_kept']['visible05']['matched']) for k,v in policies.items()},flush=True)
 (OUT/'results.json').write_text(json.dumps({'format':'r77-fixed-prompt-policies-v1','protocol_sha256':sha(OUT/'protocol.json'),'records':records,'warning':'Previously examined synthetic opaque crossings, same source pairs reused across layouts; cached predictions with no new inference or runtime measurement. Reconstructed scene RGB not directly hashed during R75 inference.'},indent=2)+'\n')
if __name__=='__main__':main()
