"""Pre-register and run a small, closed-set source-crop transfer experiment."""
import collections, ctypes, hashlib, json, os, signal, sys, time
from pathlib import Path
import numpy as np
from PIL import Image
R=Path(__file__).resolve().parents[1]; D=R/'results/r112/species-depth'; S=R/'results/r112/weak-development-v1'; H=D/'mask-hypotheses'; O=R/'results/r112/design/synthetic-training-pilot'; W=Path('/tmp/resnet18-f37072fd.pth')
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 freeze():
 O.mkdir(parents=True,exist_ok=True); assert not (O/'protocol.json').exists()
 scene=json.loads((S/'manifest.json').read_text()); sel=json.loads((D/'selection.json').read_text())['rows']; q=set(json.loads((D/'similarity-screen.json').read_text())['quarantined_new_ids']); lookup={r['annotation_id']:r for r in sel}; train={}
 for s in scene['records']:
  for i,x in enumerate(s['instances']):
   ident=x['annotation_id']; r=lookup[ident]
   if x['in_frame_fraction']>=.95 and ident not in train:
    assert r['split']=='development' and ident not in q and r['species']==x['source_species'] and r['source_slide']==x['source_slide_group']
    train[ident]={'annotation_id':ident,'species':r['species'],'source_slide':r['source_slide'],'scene_id':s['id'],'instance_index':i}
 val=[{'annotation_id':r['annotation_id'],'species':r['species'],'source_slide':r['source_slide'],'local_file':r['local_file'],'sha256':sha(D/r['local_file'])} for r in sel if r['split']=='validation_candidate' and r['annotation_id'] not in q]
 labels=sorted({r['species'] for r in train.values()}); assert len(labels)==10 and len(val)==50 and {r['species'] for r in val}==set(labels)
 assert not {r['source_slide'] for r in train.values()} & {r['source_slide'] for r in val}; assert not {r['annotation_id'] for r in train.values()} & {r['annotation_id'] for r in val}
 inputs=[S/'manifest.json',D/'selection.json',D/'similarity-screen.json',D/'development-assets.json']; p={'format':'r112-synthetic-training-pilot-v1','selection':'First scene-manifest placement per development source with at least 95% of its unverified mask support in frame, before predictions. No source or placement selected by classifier outcome.','inputs_sha256':{str(x.relative_to(R)):sha(x) for x in inputs},'encoder_sha256':sha(W),'encoder':'ImageNet pretrained ResNet-18 frozen features; grayscale input, median letterbox and ImageNet normalization; no fine-tuning.','label_order':labels,'training':list(train.values()),'validation':val,'methods':{'real':'Centroids of original source embeddings.','synthetic':'Centroids of oracle placement rectangles from composite scenes.','real_plus_synthetic':'Equal per-source weights for original and composite embeddings.','real_plus_transformed':'Equal per-source weights for original and resampled/rotated/cropped source embeddings; control for transformation and number of images.'},'fit':'Each input embedding normalized; average per class; normalize centroid. No hyperparameter tuning or unknown rejection.','evaluation':'Exactly one pass on 50 source-named validation-candidate crops from ten filename-derived slide groups; report exact-name top-1 and per-class counts. Validation is now consumed. Do not evaluate candidate test crops.','limitations':'Split by slide filename, not proven independent biological samples; 5 validation crops per class may be correlated; unverified source names; known synthetic crop rectangle is an oracle; background may contain unlabeled organisms; no end-to-end segmentation, open-set or Academy performance claim.'}; (O/'protocol.json').write_text(json.dumps(p,indent=2)+'\n');print('Frozen',len(train),'training sources and',len(val),'validation crops',flush=True)
def run():
 import torch,cv2
 from torchvision.models import resnet18
 from run_field import embedding
 from r112_weak_scenes import transform
 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 not (O/'results.json').exists()
 for k,v in p['inputs_sha256'].items():assert sha(R/k)==v
 assert sha(W)==p['encoder_sha256'];model=resnet18(weights=None);model.load_state_dict(torch.load(W,map_location='cpu',weights_only=True));model.fc=torch.nn.Identity();model.eval();scenes={s['id']:s for s in json.loads((S/'manifest.json').read_text())['records']}; feats=[];geo=[];start=time.monotonic()
 for i,r in enumerate(p['training']):
  s=scenes[r['scene_id']];v=s['instances'][r['instance_index']];assert v['annotation_id']==r['annotation_id'];source=D/v['source_original'];mask=H/v['source_mask_center'];sp=S/s['image'];assert sha(source)==v['source_original_sha256'] and sha(mask)==v['source_mask_center_sha256'] and sha(sp)==s['image_sha256'];raw=Image.open(source).convert('L');ms=np.asarray(Image.open(mask).convert('L'))>0; sx,sy=s['background_um_per_pixel_xy'];t,_,dims=transform(np.asarray(raw),ms,sx,sy,v['rotation_ccw_degrees']);valid=np.asarray(Image.new('L',tuple(dims),255).rotate(v['rotation_ccw_degrees'],resample=Image.Resampling.NEAREST,expand=True))>0;t=np.where(valid,t,int(np.median(np.asarray(raw)))).astype('uint8');h,w=t.shape;x=v['center_xy'][0]-w//2;y=v['center_xy'][1]-h//2;x0,y0=max(0,x),max(0,y);x1,y1=min(768,x+w),min(768,y+h);assert x1>x0 and y1>y0;tr=t[y0-y:y1-y,x0-x:x1-x];co=np.asarray(Image.open(sp).convert('L'))[y0:y1,x0:x1];assert co.shape==tr.shape
  feats.append(np.stack([embedding(model,raw),embedding(model,Image.fromarray(tr)),embedding(model,Image.fromarray(co))]));geo.append({'roi_xyxy':[x0,y0,x1,y1],'source_rectangle_clipped':(x0!=x or y0!=y or x1!=x+w or y1!=y+h),'in_frame_weak_support_fraction':v['in_frame_fraction']})
  if (i+1)%25==0:print('training',i+1,'/',len(p['training']),'elapsed',round(time.monotonic()-start,1),flush=True)
 feats=np.stack(feats);unit=lambda v:v/np.linalg.norm(v,axis=-1,keepdims=True); arr={'real':feats[:,0], 'synthetic':feats[:,2], 'real_plus_synthetic':(feats[:,0]+feats[:,2])/2,'real_plus_transformed':(feats[:,0]+feats[:,1])/2};cent={k:unit(np.stack([np.mean(a[np.array([r['species']==label for r in p['training']])],axis=0) for label in p['label_order']])) for k,a in arr.items()}; valid=[];records=[]
 for r in p['validation']:
  path=D/r['local_file'];assert sha(path)==r['sha256'];v=embedding(model,Image.open(path));valid.append(v);outputs={}
  for k,c in cent.items():
   scores=c@v;pred=p['label_order'][int(np.argmax(scores))];outputs[k]={'prediction':pred,'correct':pred==r['species'],'scores':[float(s) for s in scores]}
  records.append({**r,'outputs':outputs})
 valid=np.stack(valid);np.savez_compressed(O/'features.npz',training=feats,validation=valid,**{f'centroid_{k}':v for k,v in cent.items()});counts={k:sum(r['outputs'][k]['correct'] for r in records) for k in cent};out={'format':'r112-synthetic-training-pilot-results-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'features_sha256':sha(O/'features.npz'),'counts':counts,'training_geometry':geo,'validation':records};(O/'results.json').write_text(json.dumps(out,indent=2)+'\n');print('done',counts,'elapsed',round(time.monotonic()-start,1),flush=True)
if __name__=='__main__':
 if sys.argv[1]=='freeze':freeze()
 elif sys.argv[1]=='run':run()
 else:raise ValueError('choose freeze or run')
