"""Compare two translucent blending hypotheses with the fixed weak-scene baseline."""
import ctypes,hashlib,json,os,signal,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from torchvision.models import resnet18
from run_field import embedding
from r112_weak_scenes import transform,place
R=Path(__file__).resolve().parents[1];S=R/'results/r112/weak-development-v1';P=R/'results/r112/design/species-retention-corrected';O=R/'results/r112/design/species-blend-study';D=R/'results/r112/species-depth';H=D/'mask-hypotheses';CL=R/'results/pilot/ude-adaptation-within-genus/centroid-pilot/prototypes.npz';W=Path('/tmp/resnet18-f37072fd.pth');T=R/'results/pilot/ude-adaptation-within-genus/heldout-protocol.json'
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 alpha_place(canvas,im,mask,center,alpha,contrast,source_median,mode):
 h,w=mask.shape;x,y=center[0]-w//2,center[1]-h//2;x0,y0=max(0,x),max(0,y);x1,y1=min(768,x+w),min(768,y+h);support=np.zeros((768,768),bool)
 if x1<=x0 or y1<=y0:return support,None
 ms=mask[y0-y:y1-y,x0-x:x1-x];cut=im[y0-y:y1-y,x0-x:x1-x].astype('float32');support[y0:y1,x0:x1]=ms;roi=canvas[y0:y1,x0:x1];local_median=None
 if mode=='direct_alpha':target=np.clip(128.+contrast*(cut-128.),0,255)
 elif mode=='local_matched_alpha':
  ring=(cv2.dilate(support.astype('uint8'),np.ones((31,31),np.uint8))>0)&~support
  values=canvas[ring] if ring.any() else canvas[~support];assert values.size;local_median=float(np.median(values));target=np.clip(local_median+contrast*(cut-source_median),0,255)
 else:raise ValueError(mode)
 roi[ms]=np.rint((1-alpha)*roi[ms].astype('float32')+alpha*target[ms]).clip(0,255).astype('uint8');return support,local_median

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);p=json.loads((O/'protocol.json').read_text());assert sha(P/'results.json')==p['prior_results_sha256'] and sha(S/'manifest.json')==p['weak_scenes_sha256'] and sha(T)==p['classifier_protocol_sha256'] and sha(CL)==p['classifier_prototypes_sha256'] and sha(W)==p['classifier_encoder_sha256'];old=json.loads((P/'results.json').read_text());assert len(old['records'])==59;scenes={r['id']:r for r in json.loads((S/'manifest.json').read_text())['records']};labels=json.loads(T.read_text())['label_order'];cent=np.load(CL)['generic'];model=resnet18(weights=None);model.load_state_dict(torch.load(W,map_location='cpu',weights_only=True));model.fc=torch.nn.Identity();model.eval();cache={};scene_records={};rows=[];features=[];start=time.monotonic()
 for i,r in enumerate(old['records']):
  scene=scenes[r['scene_id']];ident=scene['id'];idx=r['instance_index'];assert scene['instances'][idx]['annotation_id']==r['annotation_id'];bg=R/scene['background']['path'];assert sha(bg)==scene['background']['sha256'];background=np.asarray(Image.open(bg).convert('L'));sx,sy=scene['background_um_per_pixel_xy'];archive=S/scene['mask_archive'];assert sha(archive)==scene['mask_archive_sha256'];z=np.load(archive);shape=tuple(z['support_shape']);supports=np.unpackbits(z['support_bits'])[:np.prod(shape)].reshape(shape).astype(bool);target=supports[idx];assert target.any()
  if ident not in cache:
   variants={};scene_info={}
   for mode in p['modes']:
    canvas=background.copy();medians=[]
    for j,x in enumerate(scene['instances']):
     sp=D/x['source_original'];mp=H/x['source_mask_center'];assert sha(sp)==x['source_original_sha256'] and sha(mp)==x['source_mask_center_sha256'];im=np.asarray(Image.open(sp).convert('L'));mask=np.asarray(Image.open(mp).convert('L'))>0;image,ms,dims=transform(im,mask,sx,sy,x['rotation_ccw_degrees']);assert dims==x['resampled_dimensions_px']
     if mode=='additive_v1':support=place(canvas,image,ms,x['center_xy'],x['opacity'],x['contrast'],x['source_background_median']);median=None
     else:support,median=alpha_place(canvas,image,ms,x['center_xy'],x['opacity'],x['contrast'],x['source_background_median'],mode)
     assert np.array_equal(support,supports[j]);medians.append(median)
    if mode=='additive_v1':assert sha(S/scene['image'])==scene['image_sha256'] and np.array_equal(canvas,np.asarray(Image.open(S/scene['image']).convert('L')))
    path=O/f'{ident}-{mode}.png';Image.fromarray(canvas).save(path);scene_info[mode]={'image':path.name,'sha256':sha(path),'local_medians':medians};variants[mode]=canvas
   cache[ident]=variants;scene_records[ident]=scene_info
  x0,y0,x1,y1=r['roi_xyxy'];stage={};vecs=[]
  for mode in p['modes']:
   canvas=cache[ident][mode];crop=Image.fromarray(canvas[y0:y1,x0:x1]);feature=embedding(model,crop);scores=cent@feature;prediction=labels[int(np.argmax(scores))];extreme=((canvas==0)|(canvas==255))&~((background==0)|(background==255));path=O/f"{r['annotation_id']}-{mode}-crop.png";crop.save(path);stage[mode]={'image':path.name,'image_sha256':sha(path),'prediction':prediction,'matches_source_name':prediction==r['source_species'],'scores':[float(x) for x in scores],'target_support_pixels':int(target.sum()),'new_boundary_pixels_within_target_support':int((extreme&target).sum())};vecs.append(feature)
  assert stage['additive_v1']['prediction']==r['stages']['composite']['prediction'] and stage['additive_v1']['image_sha256']==r['stages']['composite']['image_sha256'];features.append(np.stack(vecs));rows.append({'annotation_id':r['annotation_id'],'source_species':r['source_species'],'source_slide_group':r['source_slide_group'],'scene_id':ident,'instance_index':idx,'roi_xyxy':r['roi_xyxy'],'in_frame_fraction':r['in_frame_fraction'],'synthetic_overlap_pixels':r['synthetic_overlap_pixels'],'original_source_prediction':r['stages']['original']['prediction'],'original_source_match':r['stages']['original']['matches_source_name'],'source_original_crop':'../species-retention-corrected/'+r['stages']['original']['image'],'variants':stage});(O/'partial.json').write_text(json.dumps({'records':rows},indent=2)+'\n')
  if (i+1)%10==0:print(i+1,'/',len(old['records']),'elapsed',round(time.monotonic()-start,1),flush=True)
 np.savez_compressed(O/'features.npz',features=np.stack(features),annotation_ids=np.array([r['annotation_id'] for r in rows]));result={'format':'r112-species-blend-study-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'features_sha256':sha(O/'features.npz'),'labels':labels,'scene_variants':scene_records,'records':rows,'warning':'Previously viewed development samples; closed-set classifier, weak masks, source labels and optical realism unverified. Local ring can include unlabelled diatoms.'};(O/'results.json').write_text(json.dumps(result,indent=2)+'\n');print('done',len(rows),'cases',len(cache),'scenes',flush=True)
if __name__=='__main__':main()
