"""Freeze first synthetic placement for each known four-class development source."""
import collections,hashlib,json
from pathlib import Path
R=Path(__file__).resolve().parents[1];S=R/'results/r112/weak-development-v1';O=R/'results/r112/design/species-retention';P=R/'results/pilot/ude-adaptation-within-genus/heldout-protocol.json'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
old=json.loads(P.read_text());scenes=json.loads((S/'manifest.json').read_text());eligible=set(old['label_order']);seen=set();rows=[]
for r in scenes['records']:
 for j,v in enumerate(r['instances']):
  ident=v['annotation_id']
  if v['source_species'] not in eligible or ident in seen:continue
  seen.add(ident);rows.append({'annotation_id':ident,'source_species':v['source_species'],'source_slide_group':v['source_slide_group'],'scene_id':r['id'],'scene_image':r['image'],'scene_image_sha256':r['image_sha256'],'scene_mask_archive':r['mask_archive'],'scene_mask_sha256':r['mask_archive_sha256'],'instance_index':j,'source_original':v['source_original'],'source_sha256':v['source_original_sha256']})
protocol={'format':'r112-species-retention-v1','selection':'First recorded synthetic placement of each unique development source image whose source taxon is in the four-class R36 closed-set classifier; no results or visual qualities used. All scenes and sources have been examined previously, not a held-out test.','scene_manifest_sha256':sha(S/'manifest.json'),'classifier_protocol_sha256':sha(P),'classifier_prototypes_sha256':old['prototypes_sha256'],'classifier_encoder_sha256':old['encoder_sha256'],'reference_method':'Frozen R36 generic ResNet-18 four-class species centroids, no fitting, no unknown rejection. Original crop vs physically resampled/rotated crop vs composite image crop covering the known transformed source rectangle. The last crop is oracle placement, not automatic detection.','metrics':'Compare exact source-name top1 species matches, per-case prediction changes and feature cosine similarities. Split by predeclared in-frame fraction >=0.95 and geometric mask overlap, and report every selected case. These are development diagnostics, not Academy or general species accuracy.','limitations':'Source taxonomy is unverified; only four taxa, fixed small public model, separate filename-derived source slides do not establish biological independence; source and scenes have been used before. Composite crops contain overlapping original background organisms and synthetic neighbors. Crop placement uses generator provenance. Differences across stages conflate resizing, rotation, compositing, crop boundaries, clipping and background. All masks and classifications remain unverified.','records':rows};O.mkdir(parents=True,exist_ok=True);(O/'protocol.json').write_text(json.dumps(protocol,indent=2)+'\n');print('Frozen',len(rows),'unique development source specimens:',dict(collections.Counter(x['source_species'] for x in rows)))
