"""Choose weak consensus positive prompts from grouped training scenes only."""
import ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np
from diatom_pilot.weak_scene_dataset import WeakSceneDataset
R=Path(__file__).resolve().parents[1];D=R/'results/r112/grouped-synthetic';O=R/'results/r112/decoder-adaptation';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
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')
 cv2.setNumThreads(2);p=json.loads((O/'protocol.json').read_text());assert not (O/'training-prompts.json').exists()
 for f,h in p['inputs_sha256'].items():assert sha(R/f)==h
 d=WeakSceneDataset([D/'manifest.json'],include_mask_variants=True,synthetic_partition='train');assert len(d)==144;points=[(x*32+16,y*32+16) for y in range(16) for x in range(16)];rows=[];skipped=[]
 for i in range(len(d)):
  scene=d[i];variants=scene['weak_mask_proposals'];weak=scene['weak_projected_supports'];chosen=None
  for j,item in enumerate(scene['instances']):
   cons=variants[j].all(axis=0).astype('uint8');cons512=cv2.resize(cons,(512,512),interpolation=cv2.INTER_NEAREST).astype(bool)
   if int(cons512.sum())<50:continue
   pos128=cv2.resize(cons512.astype('float32'),(128,128),interpolation=cv2.INTER_AREA)>=.9
   if not pos128.any():continue
   other=np.any(np.delete(weak,j,axis=0),axis=0) if len(weak)>1 else np.zeros(weak.shape[1:],bool);other512=cv2.resize(other.astype('uint8'),(512,512),interpolation=cv2.INTER_NEAREST).astype(bool);distance=cv2.distanceTransform(cons512.astype('uint8'),cv2.DIST_L2,5);eligible=[(x,y) for x,y in points if cons512[y,x] and not other512[y,x]]
   if not eligible:continue
   point=min(eligible,key=lambda xy:(-float(distance[xy[1],xy[0]]),xy[1],xy[0]));path=O/(scene['scene_id']+'-positive.npz');np.savez_compressed(path,positive_bits=np.packbits(pos128.ravel()),positive_shape=np.array(pos128.shape));chosen={'scene_id':scene['scene_id'],'target_index':j,'annotation_id':item['annotation_id'],'source_species':item['source_species'],'prompt_xy_512':list(point),'consensus_pixels_512':int(cons512.sum()),'weak_positive_pixels_128':int(pos128.sum()),'positive_archive':path.name,'positive_sha256':sha(path),'source_scene_sha256':sha(D/(scene['scene_id']+'.png'))};break
  if chosen is None:skipped.append(scene['scene_id'])
  else:rows.append(chosen)
 result={'format':'r112-decoder-prompts-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(Path(__file__)),'candidate_scenes':len(d),'examples':rows,'skipped_scenes':skipped,'warning':p['limitations']};(O/'training-prompts.json').write_text(json.dumps(result,indent=2)+'\n');print('prepared',len(rows),'examples; skipped',len(skipped),'scenes')
if __name__=='__main__':main()
