"""Freeze the R36 generic-centroid test before reading held-out image pixels."""
import hashlib
import json
from pathlib import Path

ROOT=Path(__file__).resolve().parents[1]
DATA=ROOT/'results/pilot/ude-adaptation-within-genus'
ENCODER=Path('/tmp/resnet18-f37072fd.pth')

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


def main():
    selection=DATA/'selection.json';download=DATA/'download-report.json';validation=DATA/'centroid-pilot/validation.json';prototypes=DATA/'centroid-pilot/prototypes.npz'
    m=json.loads(selection.read_text());v=json.loads(validation.read_text());r=json.loads(download.read_text())
    if m.get('design')!='within-genus' or v.get('selection_sha256')!=sha(selection) or r.get('selection_sha256')!=sha(selection):raise ValueError('Selection mismatch')
    if r.get('cross_split_exact_image_duplicates') or v.get('generic_weights_sha256')!=sha(ENCODER):raise ValueError('Image or encoder integrity mismatch')
    if v.get('test_status')!='not used for feature extraction, fitting, model selection or scoring':raise ValueError('Test has already been used')
    if v['metrics']['generic']['top1_species_exact']!=15 or v['metrics']['generic']['validation_crops']!=16:raise ValueError('Unexpected validation selection evidence')
    if set(v['labels'])!=set(m['species']):raise ValueError('Label mismatch')
    if (DATA/'heldout-generic.json').exists():raise FileExistsError('Test already scored; do not overwrite')
    result={'format':'r36-frozen-public-protocol-v1','method':'generic_resnet18_unit_species_centroids','selection_rule':'Choose generic centroid method from fixed validation comparison by highest exact species count; no test-informed tuning.',
            'closed_set':True,'unknown_rejection':False,'training_count':64,'validation_count':16,'test_count':16,
            'label_order':v['labels'],'selection_sha256':sha(selection),'download_report_sha256':sha(download),
            'validation_sha256':sha(validation),'prototypes_sha256':sha(prototypes),'encoder_sha256':sha(ENCODER),
            'evaluation':'One frozen top-1 species and derived genus prediction per selected test crop; count exact matches and show all crops.',
            'limitations':'Selected public crop groups, not independent biological samples; no detection, unknown taxa, real crossings, or Academy performance.'}
    with (DATA/'heldout-protocol.json').open('x') as f:json.dump(result,f,indent=2);f.write('\n')
    print('Frozen test protocol written; no test image pixels read.')

if __name__=='__main__':main()
