"""Generate resumable, explicitly unverified three-prompt source-mask proposals."""
import argparse,collections,ctypes,datetime,hashlib,json,logging,os,signal,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics.models.sam import Predictor
from ultralytics.utils import LOGGER
from r112_new_taxa_masks import points_for
R=Path(__file__).resolve().parents[1];D=R/'results/r112/species-breadth-extension';O=D/'mask-hypotheses';W=Path('/tmp/mobile_sam.pt');sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def write_atomic(path,obj):
 tmp=path.with_suffix(path.suffix+'.tmp');tmp.write_text(json.dumps(obj,indent=2)+'\n');tmp.replace(path)
def existing(record,source,protocol_hash):
 if record.get('protocol_sha256')!=protocol_hash or record.get('source_sha256')!=source['source_sha256'] or record.get('annotation_id')!=source['annotation_id']:raise ValueError('Existing proposal record provenance mismatch')
 for x in record['masks'].values():
  if sha(O/x['file'])!=x['sha256']:raise ValueError('Existing proposal mask mismatch')
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')
 parser=argparse.ArgumentParser();parser.add_argument('--limit',type=int,default=0,help='Optional bound for a pilot run; zero means all');args=parser.parse_args();cv2.setNumThreads(2);torch.set_num_threads(2);LOGGER.setLevel(logging.ERROR);p=json.loads((O/'protocol.json').read_text());ph=sha(O/'protocol.json');assert sha(D/'assets.json')==p['source_assets_sha256'] and sha(D/'verify.json')==p['source_verify_sha256'] and sha(W)==p['model_sha256'] and sha(R/'research/r112_new_taxa_masks.py')==p['prompt_helper_sha256'];records=json.loads((D/'assets.json').read_text())['records'];assert len(records)==1054;predictor=Predictor(overrides={'model':str(W),'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.});start=time.monotonic();counts=collections.Counter();fail=[];processed=0;consecutive_errors=0
 for i,r in enumerate(records):
  if args.limit and processed>=args.limit:break
  ident=r['annotation_id'];assert ident.isdecimal();record_path=O/'records'/(ident+'.json')
  try:
   if record_path.exists():
    result=json.loads(record_path.read_text());existing(result,r,ph);counts[result['triage']]+=1;processed+=1;consecutive_errors=0;continue
   source=D/r['source_crop'];assert sha(source)==r['source_sha256'];im=np.asarray(Image.open(source).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;canvas=np.full((512,512),int(np.median(im)),np.uint8);canvas[oy:oy+ih,ox:ox+iw]=img;pts=points_for({**r,'source_annotation_bbox_global':r['source_bbox_global']});model_pts=[[ox+x*iw/w,oy+y*ih/h] for x,y in pts];predictor.set_image(cv2.cvtColor(canvas,cv2.COLOR_GRAY2BGR));out=predictor(points=[[[x,y]] for x,y in model_pts],labels=[[1]]*3,verbose=False)[0];assert out.masks is not None and len(out.masks.data)==3;arrays=[];saved={}
   for name,raw,score in zip(('center','minus','plus'),out.masks.data.cpu().numpy(),out.boxes.conf.cpu().numpy()):
    crop=raw[oy:oy+ih,ox:ox+iw].astype('uint8');mask=cv2.resize(crop,(w,h),interpolation=cv2.INTER_NEAREST).astype(bool);arrays.append(mask);path=O/'masks'/f'{ident}-{name}.png';tmp=path.with_suffix('.png.tmp');Image.fromarray(mask.astype('uint8')*255).save(tmp,format='PNG');tmp.replace(path);saved[name]={'file':str(path.relative_to(O)),'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((arrays[a]|arrays[b]).sum());pairs.append(int((arrays[a]&arrays[b]).sum())/union if union else 0.)
   cover=int(arrays[0].sum())/(w*h);triage='consistent-unverified' if min(pairs)>=.75 and .03<=cover<=.75 else 'needs-inspection';result={'annotation_id':ident,'source_species':r['source_species'],'source_genus':r['source_genus'],'source_site_component':r['source_site_component'],'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':saved,'pairwise_iou':pairs,'center_mask_crop_fraction':cover,'triage':triage,'protocol_sha256':ph};write_atomic(record_path,result);(O/'failures'/(ident+'.json')).unlink(missing_ok=True);counts[triage]+=1;processed+=1;consecutive_errors=0
  except Exception as exc:
   consecutive_errors+=1;processed+=1;problem={'annotation_id':ident,'error_type':type(exc).__name__,'error':str(exc),'source_sha256':r['source_sha256'],'protocol_sha256':ph};write_atomic(O/'failures'/(ident+'.json'),problem);fail.append(problem);counts['failed']+=1
   if consecutive_errors>=10:raise RuntimeError('Stopped after ten consecutive crop failures') from exc
  if processed%25==0 or processed==len(records):
   write_atomic(O/'progress.json',{'phase':'generating_unverified_proposals','processed_this_run':processed,'total_sources':len(records),'counts_this_run':dict(counts),'last_annotation_id':ident,'elapsed_seconds':round(time.monotonic()-start,1),'updated_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'note':'Last saved checkpoint; not a process liveness indicator. Existing records are checked before resume; all masks remain unverified.'})
  if processed%100==0:print('processed',processed,'/',len(records),'counts',dict(counts),'elapsed',round(time.monotonic()-start,1),flush=True)
 if not args.limit:
  done=[];missing=[]
  for r in records:
   f=O/'records'/(r['annotation_id']+'.json')
   if f.exists():
    v=json.loads(f.read_text());existing(v,r,ph);done.append(v)
   else:missing.append(r['annotation_id'])
  result={'format':p['format'],'protocol_sha256':ph,'script_sha256':sha(Path(__file__)),'source_count':len(records),'completed_count':len(done),'missing_ids':missing,'warning':p['limitations'],'records':done};write_atomic(O/'results.json',result);write_atomic(O/'progress.json',{'phase':'completed' if not missing else 'completed_with_missing','completed':len(done),'total_sources':len(records),'missing_count':len(missing),'updated_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'note':'Complete proposal generation is not proof of biological accuracy or approved training labels.'});print('complete',len(done),'missing',len(missing),flush=True)
if __name__=='__main__':main()
