"""Probe a previously calibrated R14 threshold on a locally cached UDE slide prefix."""
import hashlib
import json
import statistics
from pathlib import Path

import numpy as np
import torch
from PIL import Image,ImageDraw,ImageFont
from torchvision.models import resnet18

ROOT=Path(__file__).resolve().parent.parent
GALLERY=ROOT/'results/r7';OUT=ROOT/'results/r14/prefix'
gallery=json.loads((GALLERY/'reference-manifest.json').read_text())
queries=json.loads((OUT/'reference-manifest.json').read_text())['rows']
prior=json.loads((ROOT/'results/r14/unknown-genus-results.json').read_text())
threshold=statistics.median(f['threshold'] for f in prior['folds'])
assert not ({r['source_slide'] for r in gallery}&{r['source_slide'] for r in queries})
known={r['genus'] for r in gallery}
torch.set_num_threads(4)
model=resnet18(weights=None)
model.load_state_dict(torch.load('/tmp/resnet18-f37072fd.pth',map_location='cpu',weights_only=True))
model.fc=torch.nn.Identity();model.eval()
mean=torch.tensor([.485,.456,.406]).view(3,1,1);std=torch.tensor([.229,.224,.225]).view(3,1,1)

def prepare(base,row):
    path=base/row['local_file']
    if 'sha256' in row and hashlib.sha256(path.read_bytes()).hexdigest()!=row['sha256']:raise ValueError('Image hash mismatch')
    im=Image.open(path).convert('L');im.thumbnail((224,224),Image.Resampling.LANCZOS)
    canvas=Image.new('L',(224,224),int(np.median(np.asarray(im))))
    canvas.paste(im,((224-im.width)//2,(224-im.height)//2));return canvas

def feature(base,row):
    a=np.asarray(prepare(base,row).convert('RGB'),dtype=np.float32)/255
    with torch.inference_mode():
        v=model(((torch.from_numpy(a).permute(2,0,1)-mean)/std)[None])[0]
        return torch.nn.functional.normalize(v,dim=0).numpy()

g={r['annotation_id']:feature(GALLERY,r) for r in gallery}
records=[]
for q in queries:
    v=feature(OUT,q)
    ranked=sorted(((float(v@g[r['annotation_id']]),r) for r in gallery),key=lambda x:-x[0])
    score,neighbor=ranked[0]
    records.append({'query':q,'query_genus_in_gallery':q['genus'] in known,'score':score,'accepted':score>=threshold,
                    'top_reference_id':neighbor['annotation_id'],'top_reference_genus':neighbor['genus']})
(OUT/'abstention-results.json').write_text(json.dumps({'threshold':threshold,'threshold_source':'median of six prior R14 outer-fold thresholds, computed without this slide','gallery_genera':sorted(known),'gallery_size':len(gallery),'queries':records},indent=2))
font=ImageFont.truetype('DejaVuSans.ttf',15);plate=Image.new('RGB',(1100,len(records)*180),'#f8f8f2');d=ImageDraw.Draw(plate)
by_id={r['annotation_id']:r for r in gallery}
for i,r in enumerate(records):
    y=i*180;q=r['query'];n=by_id[r['top_reference_id']]
    d.text((8,y+4),f"UDE reference label: {q['genus']} · {q['annotation_id']} · {'genus in gallery' if r['query_genus_in_gallery'] else 'genus absent'}",font=font,fill='#193b36')
    for j,(base,row,label) in enumerate([(OUT,q,'Query'),(GALLERY,n,f"Nearest reference: {n['genus']}")]):
        x=j*360+8;d.text((x,y+25),label,font=font,fill='#193b36');plate.paste(prepare(base,row).resize((130,130)),(x,y+45))
    d.text((735,y+30),f"similarity {r['score']:.3f}",font=font,fill='#193b36')
    d.text((735,y+53),'accept' if r['accepted'] else 'abstain',font=font,fill='#193b36')
plate.save(OUT/'abstention.jpg',quality=90)
for present in (True,False):
    selected=[r for r in records if r['query_genus_in_gallery']==present]
    print('genus present',present,'queries',len(selected),'accepted',sum(r['accepted'] for r in selected),
          'accepted correct',sum(r['accepted'] and r['query']['genus']==r['top_reference_genus'] for r in selected))
print('threshold',round(threshold,6))
