"""Regenerate and validate R44's full MobileSAM candidate streams."""
import hashlib,json,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics import YOLO
from ultralytics.models.sam import Predictor
from diatom_pilot.fast_mask_nms import greedy_mask_nms
import r38_synthetic_crossings as base
import r41_consensus_fresh_sources as ranker
import r44_score_fields as evaluator
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r79';SRC=ROOT/'results/r78'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def same(a,b):
 return a['matched']==b['matched'] and a['reference_count']==b['reference_count'] and a['candidate_count']==b['candidate_count'] and np.allclose(a['ious'],b['ious'],rtol=0,atol=1e-7)
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'])
 selection=json.loads((ROOT/'results/r44/selection.json').read_text())['selection'];old={r['id']:r for r in json.loads((ROOT/'results/r44/results.json').read_text())['records']};cp={r['image_id']:r for r in json.loads((SRC/'results.json').read_text())['records'] if r['group']=='menne'};torch.set_num_threads(4);detector=YOLO(str(base.DETECTOR));records=[]
 for i,row in enumerate(selection,1):
  t=time.monotonic();r=cp[row['id']];image=np.asarray(Image.open(r['source_image_path']).convert('RGB'));assert sha(r['source_image_path'])==r['source_image_sha256'];source=np.load(SRC/r['archive'],allow_pickle=False);refs=list(source['refs_visible']);assert len(refs)==row['annotation_count'];bgr=cv2.cvtColor(image,cv2.COLOR_RGB2BGR);pred=detector.predict(bgr,imgsz=512,conf=.05,device='cpu',verbose=False)[0];boxes=pred.boxes.xyxy.cpu().numpy().tolist() if pred.boxes is not None else []
  model=Predictor(overrides={'model':str(base.SAM),'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});model.set_image(bgr)
  if boxes:
   out=model(bboxes=boxes,verbose=False)[0];det=[] if out.masks is None else [{'id':f'det-{j}','mask':m.astype(bool)} for j,m in enumerate(out.masks.data.cpu().numpy())]
  else:det=[]
  points=[(x,y) for y in range(32,512,64) for x in range(32,512,64)];raw=[]
  for n in range(0,64,12):
   batch=points[n:n+12];out=model(points=[[[x,y]] for x,y in batch],labels=[[1] for _ in batch],verbose=False)[0];assert out.masks is not None and len(out.masks.data)==len(batch)
   for pt,m,q in zip(batch,out.masks.data.cpu().numpy(),out.boxes.conf.cpu().numpy()):
    mask=m.astype(bool);quality=float(q);area=int(mask.sum());raw.append({'id':f'pt-{pt[0]}-{pt[1]}','mask':mask,'point':list(pt),'quality':quality,'eligible':300<=area<=50000 and quality>=.6})
  eligible=sorted((x for x in raw if x['eligible']),key=lambda x:-x['quality']);grid,aliases=greedy_mask_nms(eligible,.8)
  for c in grid:c['support']=max((base.iou(c['mask'],d['mask']) for d in det),default=0.)
  supported=sorted(grid,key=lambda c:(-(c['support']>=.25),-c['quality']));rank=ranker.interleave(supported,grid);combined=ranker.interleave(det,rank);prior=old[row['id']];assert len(det)==prior['detector_count'] and len(grid)==prior['grid_count'] and len(combined)==prior['combined_count']
  checks={}
  for name,items in [('grid',rank),('combined',combined)]:
   checks[name]={}
   for n in (5,10,20):
    new={'iou05':evaluator.match(refs,items[:n],.5),'iou075':evaluator.match(refs,items[:n],.75)};before=prior['scores'][name][str(n)];assert same(new['iou05'],before['iou05']) and same(new['iou075'],before['iou075']),(row['id'],name,n,new,before);checks[name][str(n)]=new
  detscore={'iou05':evaluator.match(refs,det,.5),'iou075':evaluator.match(refs,det,.75)};assert same(detscore['iou05'],prior['scores']['detector_all']['iou05']) and same(detscore['iou075'],prior['scores']['detector_all']['iou075'])
  allm=det+raw;arr=np.stack([x['mask'] for x in allm]) if allm else np.zeros((0,512,512),bool);archive=OUT/f"menne-{row['id']}-sam.npz";np.savez_compressed(archive,mask_bits=np.packbits(arr.ravel()),mask_shape=np.array(arr.shape),ids=np.array([x['id'] for x in allm]),points=np.asarray(points),quality=np.array([x['quality'] for x in raw]),eligible=np.array([x['eligible'] for x in raw]),detector_count=np.array(len(det)))
  rec={'image_id':row['id'],'source_image_sha256':r['source_image_sha256'],'cellpose_archive':r['archive'],'cellpose_archive_sha256':r['archive_sha256'],'sam_archive':archive.name,'sam_archive_sha256':sha(archive),'detector_boxes':boxes,'point_ids':[x['id'] for x in raw],'eligible_quality_order':[x['id'] for x in eligible],'grid_aliases':aliases,'grid_ranking':[x['id'] for x in rank],'combined_ranking':[x['id'] for x in combined],'reproduction_scores':checks,'detector_scores':detscore,'seconds':round(time.monotonic()-t,3)};records.append(rec);print(f"{i}/18 field {row['id']}: detector {len(det)}, grid {len(grid)}, top10 {checks['combined']['10']['iou05']['matched']}/{len(refs)} reproduced",flush=True)
 (OUT/'reproduction.json').write_text(json.dumps({'format':'r79-r44-reproduction-v1','protocol_sha256':sha(OUT/'protocol.json'),'records':records,'warning':'Reproduced saved score/count outputs; R44 did not archive masks, so exact pixel identity with its original inference cannot be directly verified.'},indent=2)+'\n')
if __name__=='__main__':main()
