"""Fixed Cellpose-SAM v2 candidate replay; checkpoint every source image."""
import hashlib,json,time,datetime
from pathlib import Path
import numpy as np,torch
from PIL import Image,ImageDraw
from cellpose import models
from l70_cellpose import match
R=Path(__file__).resolve().parents[1];O=R/'results/l79'; W=Path('/tmp/diatom-cellpose-models/cpsam_v2')
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for block in iter(lambda:f.read(1048576),b''):h.update(block)
 return h.hexdigest()
def panel(rgb,refs,masks,path):
 out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
 for k,(title,arr) in enumerate([('Source visible regions',refs),('Cellpose top 30',masks[:30]),('Cellpose all labels',masks)]):
  tile=Image.fromarray(rgb).convert('RGBA')
  for i,m in enumerate(arr):
   layer=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][i%4]);layer.putalpha(Image.fromarray(m.astype('uint8')*95));tile=Image.alpha_composite(tile,layer)
  out.paste(tile.convert('RGB').resize((350,350)),(k*360+5,35));draw.text((k*360+5,10),title,fill='#203a38')
 out.save(path)
def main():
 p=json.loads((O/'protocol.json').read_text());assert W.stat().st_size==p['model_bytes'] and sha(W)==p['model_sha256'];assert sha(R/p['source_real'])==p['source_real_sha256'] and sha(R/p['source_synthetic'])==p['source_synthetic_sha256']
 real=json.loads((R/p['source_real']).read_text())['records'];syn=[r for r in json.loads((R/p['source_synthetic']).read_text())['records'] if r['split']=='source_file_holdout' and r['condition'] in p['synthetic_selection']['conditions']];assert len(real)==11 and len(syn)==8
 torch.set_num_threads(4);model=models.CellposeModel(gpu=False,pretrained_model=str(W),use_bfloat16=False);records=[]
 for i,(group,row) in enumerate([('real',r) for r in real]+[('synthetic',r) for r in syn]):
  if group=='real':
   name='real-'+row['id'];src=R/row['source_image'];old=R/'results/r91'/row['archive'];assert sha(src)==row['source_image_sha256'] and sha(old)==row['archive_sha256'];orig=Image.open(src).convert('RGB');rgb=np.zeros((512,512,3),np.uint8);rgb[64:448]=np.asarray(orig.resize((512,384),Image.Resampling.LANCZOS));z=np.load(old);refs=z['refs'];ids=z['refids'].tolist()
  else:
   name=f"pair-{row['pair']}-{row['condition']}";src=R/'results/r91/synthetic'/row['image'];old=R/'results/r91/synthetic'/row['archive'];assert sha(src)==row['image_sha256'] and sha(old)==row['archive_sha256'];rgb=np.asarray(Image.open(src).convert('RGB'));z=np.load(old);ids=row['included_targets'];refs=z['refs'][ids]
  t=time.monotonic();labels,flows,_=model.eval(rgb,batch_size=1,channel_axis=-1,normalize=True,diameter=None,flow_threshold=.4,cellprob_threshold=0.,min_size=15,max_size_fraction=.4,niter=None,augment=False,tile_overlap=.1,bsize=256,resample=True,compute_masks=True);elapsed=time.monotonic()-t;labels=np.asarray(labels);prob=np.asarray(flows[2]);flow=np.asarray(flows[1]);assert labels.shape==prob.shape==(512,512) and np.isfinite(prob).all() and np.isfinite(flow).all()
  order=sorted((int(x) for x in np.unique(labels) if x),key=lambda x:(-float(prob[labels==x].mean()),x));masks=np.stack([labels==x for x in order]) if order else np.zeros((0,512,512),bool);scores={str(n):{str(th):match(refs,ids,masks if n=='all' else masks[:n],th) for th in (.5,.75)} for n in (10,30,'all')}
  archive=O/(name+'.npz');np.savez_compressed(archive,labels=labels,cellprob=prob,flow=flow,refs=refs,refids=np.array(ids),candidate_labels=np.array(order));picture=O/(name+'.png');panel(rgb,refs,masks,picture)
  rec={'name':name,'group':group,'condition':row.get('condition'),'source':str(src.relative_to(R)),'source_sha256':sha(src),'source_archive':str(old.relative_to(R)),'source_archive_sha256':sha(old),'references':len(refs),'candidates':len(order),'candidate_order':order,'seconds':round(elapsed,3),'scores':scores,'mobile_sam':row['models']['baseline']['scores'],'archive':archive.name,'archive_sha256':sha(archive),'image':picture.name,'image_sha256':sha(picture)};records.append(rec)
  (O/'partial-results.json').write_text(json.dumps({'records':records},indent=2)+'\n');(O/'progress.json').write_text(json.dumps({'completed':len(records),'total':19,'last_case':name,'updated_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'note':'Checkpoint timestamp; does not establish process liveness.'},indent=2)+'\n');print(f"{i+1}/19 {name} {len(order)} candidates, {scores['30']['0.5']['matched']}/{len(refs)} matched, {elapsed:.1f}s",flush=True)
 (O/'results.json').write_text(json.dumps({'format':'l79-cellpose-sam-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'model_sha256':sha(W),'records':records},indent=2)+'\n')
if __name__=='__main__':main()
