"""Score frozen unseen-genus public crops against the R36 centroids."""
import hashlib,html,json
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];OUT=ROOT/'results/r37';PREV=ROOT/'results/pilot/ude-adaptation-within-genus';ENCODER=Path('/tmp/resnet18-f37072fd.pth')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()

def main():
    if (OUT/'results.json').exists():raise FileExistsError('Frozen diagnostic already scored')
    p=json.loads((OUT/'protocol.json').read_text());m=json.loads((OUT/'selection.json').read_text());d=json.loads((OUT/'download-report.json').read_text());v=json.loads((PREV/'centroid-pilot/validation.json').read_text())
    for path,key in [(OUT/'selection.json','selection_sha256'),(ENCODER,'encoder_sha256'),(PREV/'centroid-pilot/prototypes.npz','prototypes_sha256'),(PREV/'centroid-pilot/validation.json','validation_sha256')]:
        if sha(path)!=p[key]:raise ValueError('Frozen input changed: '+key)
    if d['selection_sha256']!=sha(OUT/'selection.json') or d['cross_split_exact_image_duplicates'] or len(m['rows'])!=96:raise ValueError('Image selection mismatch')
    byid={r['annotation_id']:r for r in d['images']}
    known_hashes={r['sha256'] for r in json.loads((PREV/'download-report.json').read_text())['images']}
    unknown_hashes=[r['sha256'] for r in d['images']]
    if len(set(unknown_hashes))!=len(unknown_hashes) or known_hashes.intersection(unknown_hashes):raise ValueError('Exact duplicate images require review before scoring')
    for row in m['rows']:
        item=byid.get(row['annotation_id'])
        if not item or sha(OUT/row['local_file'])!=item['sha256']:raise ValueError('Image hash mismatch')
    with np.load(PREV/'centroid-pilot/prototypes.npz') as f:centroids=f['generic'].copy()
    model=resnet18(weights=None);model.load_state_dict(torch.load(ENCODER,map_location='cpu',weights_only=True));model.fc=torch.nn.Identity();model.eval();torch.set_num_threads(4)
    results=[]
    for i,row in enumerate(m['rows'],1):
        with Image.open(OUT/row['local_file']) as image:vector=embedding(model,image)
        scores=centroids@vector;idx=int(np.argmax(scores));confidence=float(scores[idx]);results.append({'annotation_id':row['annotation_id'],'image':row['local_file'],'source_slide':row['source_slide'],
          'species':row['species'],'genus':row['genus'],'predicted_species':v['labels'][idx],'similarity':confidence,'accepted':confidence>=p['threshold']})
        if i%16==0:print(f'{i}/96 unknown crops scored',flush=True)
    accepted=sum(x['accepted'] for x in results);groups={s:{'accepted':sum(r['accepted'] for r in results if r['source_slide']==s),'n':sum(r['source_slide']==s for r in results)} for s in sorted({r['source_slide'] for r in results})}
    payload={'format':'r37-unknown-result-v1','protocol_sha256':sha(OUT/'protocol.json'),'n':len(results),'accepted':accepted,'groups':groups,'records':results,
      'warning':'Public labeled cutouts, two selected unknown genera and filename-derived slide groups; fixed threshold from 16 known validation crops; not Academy field or probability calibration.'}
    (OUT/'results.json').write_text(json.dumps(payload,indent=2)+'\n')
    cards=[]
    for r in results[:24]:cards.append('<article><img src="'+html.escape(r['image'],quote=True)+'" alt="UDE diatom crop"><p>Dataset: '+html.escape(r['species'])+'<br>'+('Accepted wrong label: '+html.escape(r['predicted_species']) if r['accepted'] else 'Rejected as unknown')+'<br>Similarity: '+format(r['similarity'],'.3f')+'</p></article>')
    page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Unknown-genus stress test</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1150px;margin:auto;padding:24px}.notice{background:#fff2d6;padding:14px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:12px}article{background:white;padding:12px}img{width:100%;height:170px;object-fit:contain}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/research/R37.md">Research note</a></nav><h1>Unknown-genus stress test</h1><p class="notice">Selected public cutouts from two genera absent from a four-species training set. The threshold was fixed using only 16 known validation crops; slide names do not establish independent samples. This is not a calibrated probability or Academy field result.</p><p><b>{A} / {N}</b> unknown crops were accepted as one of the known species. The fixed threshold retained {K} / {V} known validation crops. The first 24 examples are shown below; <a href="results.json">all predictions</a> and the <a href="protocol.json">frozen protocol</a> are available.</p><div class="grid">{CARDS}</div></main></html>'''
    for k,x in [('A',accepted),('N',len(results)),('K',p['known_validation_accepted']),('V',p['known_validation_count']),('CARDS',''.join(cards))]:page=page.replace('{'+k+'}',str(x))
    (OUT/'index.html').write_text(page)
    note=f'''# R37 · Unseen-genus rejection diagnostic\n\nThe fixed R36 four-species generic centroid model must reject taxa outside its known classes. Before fetching unknown images, fix the threshold to the second-lowest maximum cosine similarity on 16 known validation crops, retaining {p['known_validation_accepted']}/{p['known_validation_count']} there. Select 96 public UDE crops from two previously unseen genera across 12 filename-derived slide groups, excluding prior selected slide names. This is a deliberately balanced, metadata-selected diagnostic, not a representative sample or evidence of independent biological samples.\n\nThe threshold accepted **{accepted}/{len(results)}** unknown-genus crops as one of the known species. [See examples and scores](/results/r37/), [all records](/results/r37/results.json), and [frozen protocol](/results/r37/protocol.json). Similarity is not a probability. The selected unseen genera, small calibration set and related slide groups limit generalization; there is no debris class, realistic prevalence, local Academy field evaluation, or expert adjudication. Evaluate additional unseen taxa and biological samples before selecting a rejection threshold.\n'''
    (ROOT/'research/R37.md').write_text(note)
    board=ROOT/'research/board.json';b=json.loads(board.read_text())
    for task in b['tasks']:
        if task['id']=='R37':task.update(status='review',title='Test rejection of unseen public genera',summary=f'Fixed threshold accepted {accepted}/96 crops from two unseen public genera; calibration used 16 known validation crops and slides are not proven independent.',note='R37.md',result='/results/r37/')
    temp=board.with_suffix('.json.tmp');temp.write_text(json.dumps(b,indent=2)+'\n');temp.replace(board)
    print(f'Completed frozen unknown-genus diagnostic: {accepted}/96 accepted.',flush=True)

if __name__=='__main__':main()
