"""Score the frozen R36 generic centroid method once on the public held-out crops."""
import hashlib
import html
import json
from collections import Counter
from pathlib import Path

import numpy as np
import torch
from PIL import Image
from torchvision.models import resnet18
from run_field import embedding

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():
    protocol_path=DATA/'heldout-protocol.json';p=json.loads(protocol_path.read_text());m=json.loads((DATA/'selection.json').read_text());v=json.loads((DATA/'centroid-pilot/validation.json').read_text());report=json.loads((DATA/'download-report.json').read_text())
    for path,key in [(DATA/'selection.json','selection_sha256'),(DATA/'download-report.json','download_report_sha256'),(DATA/'centroid-pilot/validation.json','validation_sha256'),(DATA/'centroid-pilot/prototypes.npz','prototypes_sha256'),(ENCODER,'encoder_sha256')]:
        if sha(path)!=p[key]:raise ValueError(f'Frozen input changed: {key}')
    if p.get('format')!='r36-frozen-public-protocol-v1' or p['label_order']!=v['labels']:raise ValueError('Invalid frozen protocol')
    out=DATA/'heldout-generic.json'
    if out.exists():raise FileExistsError('Frozen test result already exists')
    rows=[r for r in m['rows'] if r['split']=='test'];groups={r['source_slide'] for r in rows}
    if len(rows)!=p['test_count'] or len(groups)!=2:raise ValueError('Unexpected held-out test composition')
    byid={r['annotation_id']:r for r in report['images']}
    for row in rows:
        item=byid.get(row['annotation_id'])
        if not item or item['split']!='test' or sha(DATA/row['local_file'])!=item['sha256']:raise ValueError('Test image hash mismatch')
    with np.load(DATA/'centroid-pilot/prototypes.npz') as f:centroids=f['generic'].copy()
    if centroids.shape!=(len(p['label_order']),512) or not np.isfinite(centroids).all():raise ValueError('Invalid frozen centroids')
    torch.set_num_threads(4);model=resnet18(weights=None);model.load_state_dict(torch.load(ENCODER,map_location='cpu',weights_only=True));model.fc=torch.nn.Identity();model.eval();results=[]
    for row in rows:
        with Image.open(DATA/row['local_file']) as im:vector=embedding(model,im)
        similarities=centroids@vector;pred=p['label_order'][int(np.argmax(similarities))]
        results.append({'annotation_id':row['annotation_id'],'source_slide':row['source_slide'],'image':row['local_file'],'species':row['species'],'genus':row['genus'],
                        'predicted_species':pred,'predicted_genus':pred.split()[0],'similarity':float(np.max(similarities))})
    counts={'n':len(results),'slides':len(groups),'genus_correct':sum(x['genus']==x['predicted_genus'] for x in results),'species_correct':sum(x['species']==x['predicted_species'] for x in results)}
    payload={'format':'r36-public-heldout-result-v1','protocol_sha256':sha(protocol_path),'counts':counts,'records':results,
             'warning':'Selected UDE public cutouts; filename slide groups do not establish biological independence. Closed-set forced choice; not Academy field performance.'}
    with out.open('x') as f:json.dump(payload,f,indent=2);f.write('\n')
    esc=html.escape;cards=[]
    for r in results:
        good=r['species']==r['predicted_species'];cards.append('<article><img src="'+esc(r['image'],quote=True)+'" alt="Public diatom crop"><div><b>'+('Correct' if good else 'Different')+'</b><p>Dataset label: '+esc(r['species'])+'<br>Predicted: '+esc(r['predicted_species'])+'</p><small>Slide '+esc(r['source_slide'])+' · crop '+esc(r['annotation_id'])+'</small></div></article>')
    page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Public held-out species diagnostic</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1150px;margin:auto;padding:24px}a{color:#176954}.notice{background:#fff2d6;padding:14px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(340px,1fr));gap:12px}article{display:flex;gap:12px;background:white;border:1px solid #ccd9d1;padding:12px}img{width:160px;height:150px;object-fit:contain;background:#ddd}small{overflow-wrap:anywhere;color:#526c65}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/results/board.html">Research board</a> · <a href="/research/R36.md">Research note</a></nav><h1>Public held-out species diagnostic</h1><p class="notice">This is a small, selected public-data test on pre-cut specimens, not Academy microscope-field performance. The four-species classifier is forced to choose a known class; it cannot reject unknown taxa. Filename-derived slides are not verified independent biological samples.</p><p><b>Genus: GENUS / TOTAL · Species: SPECIES / TOTAL</b> on TOTAL crops from SLIDES slide groups. The method was chosen from validation before opening these test crops. <a href="heldout-protocol.json">Frozen protocol</a> · <a href="heldout-generic.json">Results and provenance</a></p><div class="grid">CARDS</div></main></html>'''
    for key,value in [('GENUS',counts['genus_correct']),('SPECIES',counts['species_correct']),('TOTAL',counts['n']),('SLIDES',counts['slides']),('CARDS',''.join(cards))]:page=page.replace(key,str(value))
    (DATA/'heldout.html').write_text(page);print(json.dumps(counts))

if __name__=='__main__':main()
