"""Build non-adjudicated mask-review batch for all gated-changed sources."""
import json
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
from diatom_pilot.ude_scaleup_dataset import sha256
R=Path(__file__).resolve().parents[1];O=R/'results/r112/gated-risk-review';A=R/'results/r112/gated-mask-risk-audit';ROOTS={'scaleup':R/'results/r112/species-scaleup','breadth':R/'results/r112/species-breadth'}
def main():
 assert not (O/'batch.json').exists();risk=json.loads((A/'results.json').read_text());verify=json.loads((A/'verify.json').read_text());assert verify['results_sha256']==sha256(A/'results.json') and len(risk['unique_sources'])==366;items=sorted(risk['unique_sources'],key=lambda x:(-(x['selected_source_coverage']>.75),-x['selected_source_coverage'],x['source_name'],x['annotation_id']));assert len({x['annotation_id'] for x in items})==366;(O/'images').mkdir(exist_ok=True);cases=[]
 for item in items:
  ident=item['annotation_id'];source_root=ROOTS[item['source_pool']];record_path=R/item['proposal_record_path'];assert sha256(record_path)==item['proposal_record_sha256'];rec=json.loads(record_path.read_text());image_path=R/item['source_crop_path'];assert sha256(image_path)==rec['source_sha256']==item['source_crop_sha256'];im=np.asarray(Image.open(image_path).convert('L'));h,w=im.shape;assert [w,h]==rec['source_dimensions_px'];masks=[]
  for k in ('center','minus','plus'):
   v=rec['masks'][k];path=source_root/'mask-hypotheses'/v['file'];assert sha256(path)==v['sha256'];m=np.asarray(Image.open(path).convert('L'))>0;assert m.shape==(h,w) and int(m.sum())==v['area_px'];masks.append(m)
  target=tuple(rec['source_points_xy'][0]);images={}
  for name,mask in [('source',None),('center',masks[0]),('minus',masks[1]),('plus',masks[2])]:
   rgb=np.repeat(im[:,:,None],3,axis=2).astype(np.float32)
   if mask is not None:
    rgb[mask]=.65*rgb[mask]+.35*np.array([30,165,255],dtype=np.float32);edge=cv2.morphologyEx(mask.astype('uint8'),cv2.MORPH_GRADIENT,np.ones((3,3),np.uint8))>0;rgb[edge]=[255,80,25]
   img=Image.fromarray(np.rint(rgb).clip(0,255).astype('uint8'));draw=ImageDraw.Draw(img);x,y=target;draw.line((x-4,y,x+4,y),fill=(255,0,180),width=1);draw.line((x,y-4,x,y+4),fill=(255,0,180),width=1);dest=O/'images'/f'{ident}-{name}.png';img.save(dest);images[name]={'path':'images/'+dest.name,'sha256':sha256(dest)}
  cases.append({'id':ident,'review_pass':1 if item['selected_source_coverage']>.75 else 2,'source_pool':item['source_pool'],'source_name':item['source_name'],'source_genus':rec['source_genus'],'source_sha256':rec['source_sha256'],'source_site_component':rec['source_site_component'],'target_point_xy':list(target),'source_dimensions_px':rec['source_dimensions_px'],'proposal_sha256':{k:rec['masks'][k]['sha256'] for k in ('center','minus','plus')},'model_triage':rec['triage'],'images':images})
 batch={'format':'r112-source-mask-review-batch-v1','selection':'All 366 unique training-source crops whose gated choice differs from center in the 573-scene variant. Sort gated selected-mask source coverage over 75% first, then decreasing selected coverage, name, and ID. This deliberately enriches flagged potentially large masks; a large mask can be correct and this is not a representative sample. 127 exact source-name strings across the two development pools. Names and choices are hidden in the interface.','inputs_sha256':{'results/r112/gated-mask-risk-audit/results.json':sha256(A/'results.json'),'results/r112/gated-mask-risk-audit/verify.json':sha256(A/'verify.json'),'results/r112/species-scaleup/mask-hypotheses/verify.json':sha256(ROOTS['scaleup']/'mask-hypotheses/verify.json'),'results/r112/species-breadth/mask-hypotheses/verify.json':sha256(ROOTS['breadth']/'mask-hypotheses/verify.json'),'research/r112_gated_risk_review_build.py':sha256(Path(__file__))},'warning':'Reviewer opinions are not verified labels; record experience and uncertainty. Neither mask geometry nor shared-model agreement proves correctness. Source images can contain neighboring organisms and original names are not certified.','cases':cases};(O/'batch.json').write_text(json.dumps(batch,indent=2)+'\n');print('created',len(cases),'cases,',sum(x['review_pass']==1 for x in cases),'coverage-priority cases,',len({x['source_name'] for x in cases}),'source-name strings')
if __name__=='__main__':main()
