"""Build reproducible, training-only review batch with three visible mask choices."""
import collections,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];D=R/'results/r112/species-scaleup';H=D/'mask-hypotheses';O=R/'results/r112/source-mask-review'
def main():
 assert not (O/'batch.json').exists();data=UDEScaleupDataset('training',include_unverified_masks=True);groups=collections.defaultdict(list)
 for i,e in enumerate(data.entries):
  record=json.loads((H/'records'/f"{e['annotation_id']}.json").read_text());assert record['source_sha256']==e['source_sha256'];groups[e['source_species']].append((i,record['triage'],e['annotation_id']))
 assert len(groups)==80;cases=[];(O/'images').mkdir(exist_ok=True)
 for name in sorted(groups):
  candidates=sorted(groups[name],key=lambda x:x[2]);preferred=[x for x in candidates if x[1]=='consistent-unverified'];inspect=[x for x in candidates if x[1]=='needs-inspection'];first=(preferred or inspect)[0];second=next(x for x in (inspect+preferred) if x[2]!=first[2])
  for slot,(idx,triage,ident) in enumerate((first,second)):
   x=data[idx];rec=json.loads((H/'records'/f'{ident}.json').read_text());source=np.asarray(x['image']);maskset=x['weak_mask_proposals'];target=tuple(rec['source_points_xy'][0]);images={}
   for k,mask in [('source',None),('center',maskset[0]),('minus',maskset[1]),('plus',maskset[2])]:
    a=np.repeat(source[:,:,None],3,axis=2).astype(np.float32)
    if mask is not None:
     a[mask]=.65*a[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;a[edge]=[255,80,25]
    im=Image.fromarray(np.rint(a).clip(0,255).astype('uint8'));draw=ImageDraw.Draw(im);cx,cy=target;draw.line((cx-4,cy,cx+4,cy),fill=(255,0,180),width=1);draw.line((cx,cy-4,cx,cy+4),fill=(255,0,180),width=1);path=O/'images'/f'{ident}-{k}.png';im.save(path);images[k]={'path':'images/'+path.name,'sha256':sha(path)}
   cases.append({'id':ident,'review_pass':slot+1,'source_name':x['source_name'],'source_genus':x['source_genus'],'source_sha256':rec['source_sha256'],'source_site_component':x['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':triage,'images':images})
 cases.sort(key=lambda x:(x['review_pass'],x['source_name'],x['id']));batch={'format':'r112-source-mask-review-batch-v1','selection':'Two distinct training-only source crops per source-name string: first prefers geometry-consistent model proposals, second prefers geometry-disagreement cases where present; selected by lexicographic annotation ID, not visual quality. 160 examples span 80 names. All names and masks remain unverified for Academy taxonomy and biology.','mask_protocol_sha256':sha(H/'protocol.json'),'mask_verification_sha256':sha(H/'verify.json'),'source_partition_sha256':sha(D/'location-partitions.json'),'source_assets_sha256':sha(D/'assets.json'),'warning':'These are reviewer opinions, not verified labels. Nonexpert and expert feedback must remain distinguishable. Source crop or background may contain neighboring organisms. No taxonomy is being certified.','cases':cases};(O/'batch.json').write_text(json.dumps(batch,indent=2)+'\n');print('created',len(cases),'cases; second cases with model disagreement',sum(x['review_pass']==2 and x['model_triage']=='needs-inspection' for x in cases))
if __name__=='__main__':main()
