"""Reproduce the fixed R48 sparse MobileSAM stream and archive every mask."""
import hashlib,json,time,xml.etree.ElementTree as ET
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.mask_component_guard import candidates_from_binary
from diatom_pilot.fast_mask_nms import greedy_mask_nms
from r80_progress import update
import r38_synthetic_crossings as base
import r41_consensus_fresh_sources as ranker
import r44_score_fields as matchlib
R=Path(__file__).resolve().parents[1];O=R/'results/r80'
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((O/'protocol.json').read_text())
 for x in p['inputs']:
  if sha(x['path'])!=x['sha256']:raise ValueError('Changed input: '+x['path'])
 source=json.loads((O/'source-audit.json').read_text())['targets'];old={x['id']:x for x in json.loads((R/'results/r48/results.json').read_text())['records']};torch.set_num_threads(4);detector=YOLO(str(base.DETECTOR));records=[]
 for n,row in enumerate(source,1):
  ident=row['id'];checkpoint=O/f'sam-{ident}.json'
  if checkpoint.exists():
   rec=json.loads(checkpoint.read_text());assert rec['protocol_sha256']==sha(O/'protocol.json') and sha(O/rec['archive'])==rec['archive_sha256'];records.append(rec);update('MobileSAM replay',n,len(source),f'Recovered validated checkpoint for case {ident}.');continue
  start=time.monotonic();im=Image.open(row['image_path']).convert('RGB');ms=np.asarray(Image.open(row['mask_path']).convert('RGB'));h,w=ms.shape[:2];assert im.size==(w,h) and ((((ms==0).all(axis=2))|((ms==255).all(axis=2))).all());xml=ET.fromstring(Path(row['xml_path']).read_bytes());boxes=[[int(o.findtext('./bbox/'+k)) for k in ('xmin','ymin','xmax','ymax')] for o in xml.findall('./objects/object')];source_mask=(ms!=0).any(axis=2);struct=candidates_from_binary(source_mask,boxes,minimum_area=20,containment=.98);assert struct['status']=='structural_match';_,components,_,_=cv2.connectedComponentsWithStats(source_mask.astype('uint8'),connectivity=8);refs=[cv2.resize((components==a['component_label']).astype('uint8'),(768,576),interpolation=cv2.INTER_NEAREST)>0 for a in struct['instances']];assert len(refs)==old[ident]['reference_count'] and all(r.any() for r in refs)
  rgb=np.asarray(im.resize((768,576),Image.Resampling.LANCZOS));bgr=cv2.cvtColor(rgb,cv2.COLOR_RGB2BGR);res=detector.predict(bgr,imgsz=768,conf=.05,device='cpu',verbose=False)[0];detboxes=res.boxes.xyxy.cpu().numpy().tolist() if res.boxes is not None else [];model=Predictor(overrides={'model':str(base.SAM),'task':'segment','mode':'predict','imgsz':768,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});model.set_image(bgr)
  if detboxes:
   pred=model(bboxes=detboxes,verbose=False)[0];det=[] if pred.masks is None else [{'id':f'det-{i}','mask':m.astype(bool)} for i,m in enumerate(pred.masks.data.cpu().numpy())]
  else:det=[]
  points=[(x,y) for y in range(32,576,64) for x in range(32,768,64)];assert len(points)==108;raw=[]
  for i in range(0,len(points),12):
   batch=points[i:i+12];pred=model(points=[[[x,y]] for x,y in batch],labels=[[1] for _ in batch],verbose=False)[0];assert pred.masks is not None and len(pred.masks.data)==len(batch)
   for pt,m,q in zip(batch,pred.masks.data.cpu().numpy(),pred.boxes.conf.cpu().numpy()):
    mask=m.astype(bool);area=int(mask.sum());quality=float(q);raw.append({'id':f'pt-{pt[0]}-{pt[1]}','mask':mask,'quality':quality,'eligible':300<=area<=50000 and quality>=.6})
  eligible=sorted((q for q in raw if q['eligible']),key=lambda q:-q['quality']);grid,aliases=greedy_mask_nms(eligible,.8)
  for c in grid:c['support']=max((base.iou(c['mask'],v['mask']) for v 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);before=old[ident]['variants']['64'];assert len(grid)==before['grid_candidates'];scores={}
  for budget in (5,10,20):
   scores[str(budget)]={'iou05':matchlib.match(refs,combined[:budget],.5),'iou075':matchlib.match(refs,combined[:budget],.75)}
   for key in ('iou05','iou075'):assert same(scores[str(budget)][key],before['budgets'][str(budget)][key]),(ident,budget,key)
  allscore=matchlib.match(refs,combined,.5);assert same(allscore,before['all_candidates']),ident
  allm=det+raw;stack=np.stack([x['mask'] for x in allm]);archive=O/f'sam-{ident}.npz';np.savez_compressed(archive,mask_bits=np.packbits(stack.ravel()),mask_shape=np.array(stack.shape),ids=np.array([x['id'] for x in allm]),points=np.asarray(points),quality=np.asarray([x['quality'] for x in raw]),eligible=np.asarray([x['eligible'] for x in raw]),detector_count=np.array(len(det)),refs=np.stack(refs));record={'id':ident,'protocol_sha256':sha(O/'protocol.json'),'archive':archive.name,'archive_sha256':sha(archive),'detector_boxes':detboxes,'instances':struct['instances'],'eligible_quality_order':[q['id'] for q in eligible],'grid_aliases':aliases,'grid_ranking':[q['id'] for q in rank],'combined_ranking':[q['id'] for q in combined],'scores':scores,'all_iou05':allscore,'seconds':round(time.monotonic()-start,3)};checkpoint.write_text(json.dumps(record,indent=2)+'\n');records.append(record);update('MobileSAM replay',n,len(source),f'Case {ident}: baseline scores reproduced.');print(f'{n}/24 case {ident}: {scores["10"]["iou05"]["matched"]}/{len(refs)}, grid {len(grid)}',flush=True)
 (O/'baseline.json').write_text(json.dumps({'format':'r80-sam-reproduction-v1','protocol_sha256':sha(O/'protocol.json'),'records':records,'warning':'R48 model masks were not saved; matching score reproduction does not prove exact original inference pixels.'},indent=2)+'\n');update('MobileSAM replay complete',len(source),len(source),'All source cases match R48 baseline scores; starting Cellpose next.')
if __name__=='__main__':main()
