"""Freeze a foreground/background unknown-rejection experiment on UDE."""
import collections,csv,hashlib,json,random
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from torchvision.models import resnet18
from run_field import embedding
ROOT=Path(__file__).resolve().parents[1];PREV=ROOT/'results/pilot/ude-adaptation-within-genus';OUT=ROOT/'results/l29';META=Path('/tmp/ude-metadata.csv');ENC=Path('/tmp/resnet18-f37072fd.pth');TAXA=('Cocconeis placentula','Planothidium lanceolatum')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def unit(x):
 n=np.linalg.norm(x)
 if n<=0:raise ValueError('Empty centroid')
 return x/n
def views(image):
 arr=np.asarray(image.convert('RGB'));gray=cv2.cvtColor(arr,cv2.COLOR_RGB2GRAY);_,mask=cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU);foreground=mask>0
 # Deliberately simple intensity partition; no claim this is a specimen mask.
 background_color=np.median(arr.reshape(-1,3),axis=0).astype('uint8');fg=arr.copy();bg=arr.copy();fg[~foreground]=background_color;bg[foreground]=background_color
 return {'full':image.convert('RGB'),'dark_partition':Image.fromarray(fg),'complement':Image.fromarray(bg)}
def main():
 if (OUT/'protocol.json').exists() or (OUT/'selection.json').exists():raise FileExistsError('Frozen experiment exists')
 old=json.loads((PREV/'selection.json').read_text());download=json.loads((PREV/'download-report.json').read_text());val=json.loads((PREV/'centroid-pilot/validation.json').read_text())
 if sha(META)!=old['metadata_sha256'] or sha(PREV/'selection.json')!=download['selection_sha256'] or sha(ENC)!=val['generic_weights_sha256']:raise ValueError('Known-data integrity mismatch')
 excluded={r['source_slide'] for r in old['rows']}
 for file in (ROOT/'results/pilot/ude-adaptation/selection.json',ROOT/'results/r37/selection.json'):excluded.update(r['source_slide'] for r in json.loads(file.read_text())['rows'])
 excluded.update(r['source_slide'] for r in json.loads((ROOT/'results/r7/reference-manifest.json').read_text()));excluded.update(r['source_slide'] for r in json.loads((ROOT/'results/r14/prefix/reference-manifest.json').read_text())['rows'])
 groups=collections.defaultdict(lambda:collections.defaultdict(list))
 with META.open(encoding='utf-8-sig',newline='') as f:
  for r in csv.DictReader(f):
   slide=r['image_filename'].split('.Chunk')[0]
   if r['species'] not in TAXA or slide in excluded:continue
   w=int(r['bbox_x1'])-int(r['bbox_x0']);h=int(r['bbox_y1'])-int(r['bbox_y0'])
   if 80<=max(w,h)<=500:groups[slide][r['species']].append(r)
 eligible=sorted(s for s,g in groups.items() if all(len(g[t])>=4 for t in TAXA));rng=random.Random(20261204)
 if len(eligible)<8:raise ValueError('Insufficient eligible slide-name groups')
 rows=[];seen=set()
 for slide in rng.sample(eligible,8):
  for taxon in TAXA:
   pool=sorted(groups[slide][taxon],key=lambda x:(x['cutout_filename'],x['annotation_id']))
   for r in rng.sample(pool,4):
    if r['cutout_filename'] in seen:raise ValueError('Duplicate cutout')
    seen.add(r['cutout_filename']);rows.append({'split':'test','source_slide':slide,'species':r['species'],'genus':r['genus'],'annotation_id':r['annotation_id'],'filename':r['cutout_filename'],'image_id':r['image_id'],'local_file':'images/'+r['annotation_id']+'.png'})
 OUT.mkdir(parents=True,exist_ok=True);selection=OUT/'selection.json';selection.write_text(json.dumps({'format':'ude-four-species-development-v1','design':'foreground-background-unknown','seed':20261204,'metadata_sha256':sha(META),'species':list(TAXA),'rows':rows},indent=2)+'\n')
 byid={r['annotation_id']:r for r in download['images']};known=[r for r in old['rows'] if r['split'] in ('train','validation')]
 for r in known:
  if sha(PREV/r['local_file'])!=byid[r['annotation_id']]['sha256']:raise ValueError('Known crop hash mismatch')
 model=resnet18(weights=None);model.load_state_dict(torch.load(ENC,map_location='cpu',weights_only=True));model.fc=torch.nn.Identity();model.eval();torch.set_num_threads(4);features=[]
 for i,r in enumerate(known,1):
  with Image.open(PREV/r['local_file']) as f:images=views(f)
  features.append({'row':r,'vectors':{name:embedding(model,im) for name,im in images.items()}})
  if i%16==0:print(f'{i}/80 known crops encoded in three views',flush=True)
 labels=val['labels'];prototypes={};thresholds={}
 for name in ('full','dark_partition','complement'):
  prototypes[name]=np.stack([unit(np.mean([x['vectors'][name] for x in features if x['row']['split']=='train' and x['row']['species']==label],axis=0)) for label in labels])
  scores=sorted(float(np.max(prototypes[name]@x['vectors'][name])) for x in features if x['row']['split']=='validation');thresholds[name]=scores[1]
 np.savez_compressed(OUT/'prototypes.npz',**prototypes)
 protocol={'format':'l29-frozen-protocol-v1','selection_sha256':sha(selection),'metadata_sha256':sha(META),'encoder_sha256':sha(ENC),'known_selection_sha256':sha(PREV/'selection.json'),'known_download_sha256':sha(PREV/'download-report.json'),'prototypes_sha256':sha(OUT/'prototypes.npz'),'labels':labels,'thresholds':thresholds,'rule':'Each view uses its own second-lowest score on 16 known validation crops; retain at least 15 of 16.', 'partition':'Otsu dark pixels versus complement; removed pixels replaced by per-image median RGB; not a verified mask.'}
 (OUT/'protocol.json').write_text(json.dumps(protocol,indent=2)+'\n');print('Frozen 64 unknown crops, three view prototypes and validation thresholds.',flush=True)
if __name__=='__main__':main()
