"""Small nested slide-held-out unknown-genus rejection diagnostic on UDE cutouts."""
import json
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
REF=ROOT/'results/r7'
OUT=ROOT/'results/r14'
OUT.mkdir(exist_ok=True)
rows=json.loads((REF/'reference-manifest.json').read_text())
slides=sorted({r['source_slide'] for r in rows})
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(row):
    image=Image.open(REF/row['local_file']).convert('L')
    image.thumbnail((224,224),Image.Resampling.LANCZOS)
    canvas=Image.new('L',(224,224),int(np.median(np.asarray(image))))
    canvas.paste(image,((224-image.width)//2,(224-image.height)//2))
    return canvas

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

features={r['annotation_id']:feature(r) for r in rows}
def nearest(query,gallery,unknown):
    candidates=[r for r in gallery if not unknown or r['genus']!=query['genus']]
    assert candidates and all(r['source_slide']!=query['source_slide'] for r in candidates)
    if unknown: assert all(r['genus']!=query['genus'] for r in candidates)
    ranked=sorted(((float(features[query['annotation_id']]@features[r['annotation_id']]),r) for r in candidates),key=lambda a:a[0],reverse=True)
    score,item=ranked[0]
    return {'score':score,'neighbor_id':item['annotation_id'],'neighbor_genus':item['genus']}

folds=[]
records=[]
for test_slide in slides:
    cal=[]
    for validation_slide in slides:
        if validation_slide==test_slide: continue
        gallery=[r for r in rows if r['source_slide'] not in (test_slide,validation_slide)]
        for q in [r for r in rows if r['source_slide']==validation_slide]:
            cal.append((nearest(q,gallery,False)['score'],True))
            cal.append((nearest(q,gallery,True)['score'],False))
    values=sorted({v for v,_ in cal})
    candidates=[values[0]-1e-6]+[(a+b)/2 for a,b in zip(values,values[1:])]+[values[-1]+1e-6]
    # Balanced accuracy; select the higher threshold in ties, making abstention conservative.
    def balanced(t):
        positives=[score>=t for score,known in cal if known]
        negatives=[score<t for score,known in cal if not known]
        return (sum(positives)/len(positives)+sum(negatives)/len(negatives))/2
    threshold=max(candidates,key=lambda t:(balanced(t),t))
    folds.append({'test_slide':test_slide,'threshold':threshold,'calibration_balanced_accuracy':balanced(threshold),
                  'calibration_observations':len(cal),'calibration_gallery_slides':4,'test_gallery_slides':5})
    gallery=[r for r in rows if r['source_slide']!=test_slide]
    for q in [r for r in rows if r['source_slide']==test_slide]:
        known=nearest(q,gallery,False);unknown=nearest(q,gallery,True)
        for result in (known,unknown):result['accepted']=result['score']>=threshold
        records.append({'query':q,'threshold':threshold,'known':known,'unknown':unknown})

result={'folds':folds,'queries':records}
(OUT/'unknown-genus-results.json').write_text(json.dumps(result,indent=2))
font=ImageFont.truetype('DejaVuSans.ttf',15)
plate=Image.new('RGB',(1120,len(records)*200),'#f8f8f2');d=ImageDraw.Draw(plate)
by_id={r['annotation_id']:r for r in rows}
for i,r in enumerate(records):
    y=i*200;q=r['query'];known=r['known'];unknown=r['unknown']
    d.text((8,y+3),f"Query {q['genus']} · {q['annotation_id']} · test slide {slides.index(q['source_slide'])+1} · threshold {r['threshold']:.3f}",font=font,fill='#193b36')
    views=[(q,'Query'),(by_id[known['neighbor_id']],f"Present: {known['neighbor_genus']}"),
           (by_id[unknown['neighbor_id']],f"Withheld: {unknown['neighbor_genus']}")]
    for j,(item,title) in enumerate(views):
        x=j*365+8
        d.text((x,y+28),title,font=font,fill='#193b36')
        if j:
            res=known if j==1 else unknown
            d.text((x,y+49),f"{res['score']:.3f} · {'accept' if res['accepted'] else 'abstain'}",font=font,fill='#193b36')
        plate.paste(prepare(item).resize((125,125)),(x,y+72))
plate.save(OUT/'unknown-genus.jpg',quality=90)
print('queries',len(records),'known accepted',sum(r['known']['accepted'] for r in records),
      'known accepted correct genus',sum(r['known']['accepted'] and r['known']['neighbor_genus']==r['query']['genus'] for r in records),
      'unknown rejected',sum(not r['unknown']['accepted'] for r in records))
print('fold thresholds',[(round(f['threshold'],4),round(f['calibration_balanced_accuracy'],3)) for f in folds])
