"""Freeze an unseen-genus UDE diagnostic before downloading its pixels."""
import collections,csv,hashlib,json,random
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];META=Path('/tmp/ude-metadata.csv');OUT=ROOT/'results/r37';PREV=ROOT/'results/pilot/ude-adaptation-within-genus';taxa=('Amphora pediculus','Nitzschia soratensis');seed=20261203

def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()

def main():
    out=OUT/'selection.json';protocol=OUT/'protocol.json'
    if out.exists() or protocol.exists():raise FileExistsError('Selection or protocol exists')
    old=json.loads((PREV/'selection.json').read_text());val=json.loads((PREV/'centroid-pilot/validation.json').read_text())
    if sha(META)!=old['metadata_sha256'] or sha(PREV/'selection.json')!=val['selection_sha256']:raise ValueError('Metadata or validation mismatch')
    excluded={r['source_slide'] for r in old['rows']}
    for file in (ROOT/'results/pilot/ude-adaptation/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'])
    byslide=collections.defaultdict(lambda:collections.defaultdict(list))
    with META.open(encoding='utf-8-sig',newline='') as f:
        for r in csv.DictReader(f):
            if r['species'] not in taxa:continue
            slide=r['image_filename'].split('.Chunk')[0]
            if 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:byslide[slide][r['species']].append(r)
    eligible=sorted(s for s,g in byslide.items() if all(len(g[t])>=4 for t in taxa));rng=random.Random(seed)
    if len(eligible)<12:raise ValueError('Insufficient unexamined slide-name groups')
    slides=rng.sample(eligible,12);rows=[];seen=set()
    for slide in slides:
        for taxon in taxa:
            pool=sorted(byslide[slide][taxon],key=lambda r:(r['cutout_filename'],r['annotation_id']))
            for r in rng.sample(pool,4):
                if r['cutout_filename'] in seen:raise ValueError('Duplicate cutout name')
                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'})
    if len(rows)!=96:raise ValueError('Unexpected size')
    scores=sorted(r['predictions']['generic']['similarity'] for r in val['records']);threshold=scores[1]
    OUT.mkdir(parents=True,exist_ok=True)
    out.write_text(json.dumps({'format':'ude-four-species-development-v1','design':'unknown-genus-only','seed':seed,'metadata_sha256':sha(META),'species':list(taxa),'eligible_slide_names':len(eligible),'rows':rows},indent=2)+'\n')
    protocol.write_text(json.dumps({'format':'r37-unknown-protocol-v1','selection_sha256':sha(out),'encoder_sha256':sha(Path('/tmp/resnet18-f37072fd.pth')),
     'prototypes_sha256':sha(PREV/'centroid-pilot/prototypes.npz'),'validation_sha256':sha(PREV/'centroid-pilot/validation.json'),
     'threshold':threshold,'threshold_rule':'accept maximum cosine similarity >= second-smallest among 16 known validation crops',
     'known_validation_accepted':sum(x>=threshold for x in scores),'known_validation_count':len(scores),
     'goal':'Measure false acceptance of images from two genera absent from four forced-choice training classes; no tuning on these images.'},indent=2)+'\n')
    print('Frozen 96 unseen-genus crops across 12 filename slide groups; validation threshold',threshold)
if __name__=='__main__':main()
