"""Generate separate, unverified point-prompt mask hypotheses for development crops."""
import ctypes,hashlib,json,os,signal,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics.models.sam import Predictor
R=Path(__file__).resolve().parents[1];D=R/'results/r112/species-depth';O=D/'mask-hypotheses';NAMES=('center','minus','plus')
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(1048576),b''):h.update(b)
 return h.hexdigest()
def points_for(r):
 points=np.asarray(r['source_annotation_points_global'],dtype='float64');bx,by,*_=r['source_annotation_bbox_global'];w,h=r['source_dimensions_px'];shape=r['source_annotation_shape']
 if shape=='Rectangle':
  p=points.reshape(-1,2);assert len(p)==4;center=p.mean(axis=0);edges=np.roll(p,-1,axis=0)-p;long=edges[int(np.argmax(np.linalg.norm(edges,axis=1)))];delta=long*.2
 elif shape=='Circle':
  assert len(points)==3;center=points[:2];delta=np.array([points[2]*.35,0])
 else:raise ValueError('Unsupported annotation type: '+shape)
 return [[float(np.clip(v[0]-bx,0,w-1)),float(np.clip(v[1]-by,0,h-1))] for v in (center,center-delta,center+delta)]
def main():
 parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
 if parent!=os.getppid():raise RuntimeError('launcher exited')
 torch.set_num_threads(2);cv2.setNumThreads(2);proto=json.loads((O/'protocol.json').read_text());assert sha(D/'development-assets.json')==proto['development_assets_sha256'] and sha('/tmp/mobile_sam.pt')==proto['checkpoint_sha256'];records=json.loads((D/'development-assets.json').read_text())['records'];assert all(r['split']=='development' for r in records);out=[];start=time.monotonic()
 for i,r in enumerate(records):
  src=D/r['source_crop'];assert sha(src)==r['source_sha256'];im=np.asarray(Image.open(src).convert('L'));h,w=im.shape;assert [w,h]==r['source_dimensions_px'];factor=min(1.,512/max(w,h));iw,ih=max(1,round(w*factor)),max(1,round(h*factor));img=im if (iw,ih)==(w,h) else cv2.resize(im,(iw,ih),interpolation=cv2.INTER_AREA);ox,oy=(512-iw)//2,(512-ih)//2;can=np.full((512,512),int(np.median(im)),np.uint8);can[oy:oy+ih,ox:ox+iw]=img;pts=points_for(r);model_pts=[[ox+x*iw/w,oy+y*ih/h] for x,y in pts];model=Predictor(overrides={'model':'/tmp/mobile_sam.pt','task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.,'retina_masks':True});model.set_image(cv2.cvtColor(can,cv2.COLOR_GRAY2BGR));pred=model(points=[[[x,y]] for x,y in model_pts],labels=[[1]]*3,verbose=False)[0];assert len(pred.masks.data)==3;masks=[];q=[];paths={}
  for name,raw,score in zip(NAMES,pred.masks.data.cpu().numpy(),pred.boxes.conf.cpu().numpy()):
   part=raw[oy:oy+ih,ox:ox+iw].astype('uint8');mask=cv2.resize(part,(w,h),interpolation=cv2.INTER_NEAREST).astype(bool);masks.append(mask);q.append(float(score));path=O/f"{r['annotation_id']}-{name}.png";Image.fromarray(mask.astype('uint8')*255).save(path);paths[name]={'file':path.name,'sha256':sha(path),'area_px':int(mask.sum()),'quality_model_score_not_accuracy':float(score)}
  pairs=[]
  for a,b in ((0,1),(0,2),(1,2)):
   union=int((masks[a]|masks[b]).sum());pairs.append(int((masks[a]&masks[b]).sum())/union if union else 0.)
  coverage=int(masks[0].sum())/(w*h);status='consistent-unverified' if min(pairs)>=.75 and .03<=coverage<=.75 else 'needs-inspection';out.append({'annotation_id':r['annotation_id'],'source_species':r['source_species'],'source_slide_group':r['source_slide_group'],'source_crop':r['source_crop'],'source_sha256':r['source_sha256'],'source_dimensions_px':[w,h],'inference_input_size_px':[iw,ih],'inference_padding_offset_xy':[ox,oy],'source_points_xy':pts,'inference_points_xy':model_pts,'masks':paths,'pairwise_iou':pairs,'center_mask_crop_fraction':coverage,'triage':status});(O/'partial.json').write_text(json.dumps({'records':out},indent=2)+'\n')
  if (i+1)%20==0:print(i+1,'/',len(records),'elapsed',round(time.monotonic()-start,1),flush=True)
 result={'format':'r112-mask-hypotheses-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'warning':'All masks are unverified model hypotheses; agreement is not correctness. Source taxonomy and masks may be wrong. Background labels remain unknown. No validation or test images processed.','records':out};(O/'results.json').write_text(json.dumps(result,indent=2)+'\n');print('done',len(out),'elapsed',round(time.monotonic()-start,1))
if __name__=='__main__':main()
