"""Compare separately calibrated original and rotation-pooled open-set similarity gates."""
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
G=ROOT/'results/r7';Q=ROOT/'results/r14/prefix'
gallery=json.loads((G/'reference-manifest.json').read_text())
queries=json.loads((Q/'reference-manifest.json').read_text())['rows']
slides=sorted({r['source_slide'] for r in gallery})
assert len(slides)==6 and not set(slides)&{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,turn=0):
    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')
    for _ in range(turn):im=im.transpose(Image.Transpose.ROTATE_90)
    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 embeddings(base,row):
    batch=[]
    for turn in range(4):
        a=np.asarray(prepare(base,row,turn).convert('RGB'),dtype=np.float32)/255
        batch.append((torch.from_numpy(a).permute(2,0,1)-mean)/std)
    with torch.inference_mode():
        v=torch.nn.functional.normalize(model(torch.stack(batch)),dim=1)
        avg=torch.nn.functional.normalize(v.mean(dim=0),dim=0)
    return (v[0].numpy(),avg.numpy())

features={r['annotation_id']:embeddings(G,r) for r in gallery}
features.update({r['annotation_id']:embeddings(Q,r) for r in queries})
def nearest(q,candidates,kind):
    v=features[q['annotation_id']][kind]
    score,row=max(((float(v@features[r['annotation_id']][kind]),r) for r in candidates),key=lambda x:x[0])
    return score,row

def calibrate(kind):
    thresholds=[]
    for test_slide in slides:
        scores=[]
        for validation_slide in slides:
            if validation_slide==test_slide:continue
            pool=[r for r in gallery if r['source_slide'] not in (test_slide,validation_slide)]
            for q in [r for r in gallery if r['source_slide']==validation_slide]:
                scores.append((nearest(q,pool,kind)[0],True))
                scores.append((nearest(q,[r for r in pool if r['genus']!=q['genus']],kind)[0],False))
        values=sorted({v for v,_ in scores})
        choices=[values[0]-1e-6]+[(a+b)/2 for a,b in zip(values,values[1:])]+[values[-1]+1e-6]
        def balanced(t):
            pos=[s>=t for s,k in scores if k];neg=[s<t for s,k in scores if not k]
            return (sum(pos)/len(pos)+sum(neg)/len(neg))/2
        thresholds.append(max(choices,key=lambda t:(balanced(t),t)))
    return thresholds

fold_thresholds=[calibrate(k) for k in range(2)]
thresholds=[statistics.median(v) for v in fold_thresholds]
prior=json.loads((ROOT/'results/r14/prefix/abstention-results.json').read_text())
assert abs(prior['threshold']-thresholds[0])<1e-6
records=[]
for q in queries:
    result={'query':q,'query_genus_in_gallery':q['genus'] in known}
    for kind,name in enumerate(('original','rotation_pooled')):
        score,match=nearest(q,gallery,kind)
        result[name]={'score':score,'accepted':score>=thresholds[kind],'neighbor_id':match['annotation_id'],'neighbor_genus':match['genus']}
    records.append(result)
prior_by_id={r['query']['annotation_id']:r for r in prior['queries']}
assert all(r['original']['accepted']==prior_by_id[r['query']['annotation_id']]['accepted'] for r in records)
payload={'thresholds':dict(zip(('original','rotation_pooled'),thresholds)),'fold_thresholds':dict(zip(('original','rotation_pooled'),fold_thresholds)),
         'calibration':'median of 6 nested slide-held-out balanced-accuracy thresholds, calculated independently per representation using only original 18 references',
         'queries':records}
(Q/'rotation-abstention.json').write_text(json.dumps(payload,indent=2))
font=ImageFont.truetype('DejaVuSans.ttf',15);plate=Image.new('RGB',(1130,len(records)*175),'#f8f8f2');d=ImageDraw.Draw(plate)
by_id={r['annotation_id']:r for r in gallery}
for i,r in enumerate(records):
    y=i*175;q=r['query'];d.text((8,y+3),f"Query {q['genus']} · {'present' if r['query_genus_in_gallery'] else 'absent'} in gallery",font=font,fill='#193b36')
    views=[(Q,q,'Query'),(G,by_id[r['original']['neighbor_id']],'Original: '+r['original']['neighbor_genus']),
           (G,by_id[r['rotation_pooled']['neighbor_id']],'Pooled: '+r['rotation_pooled']['neighbor_genus'])]
    for j,(base,row,title) in enumerate(views):
        x=j*365+8;d.text((x,y+25),title,font=font,fill='#193b36')
        if j:
            v=r['original' if j==1 else 'rotation_pooled']
            d.text((x,y+45),f"{v['score']:.3f} · {'accept' if v['accepted'] else 'abstain'}",font=font,fill='#193b36')
        plate.paste(prepare(base,row).resize((100,100)),(x,y+70))
plate.save(Q/'rotation-abstention.jpg',quality=90)
for name in ('original','rotation_pooled'):
    print(name,'threshold',round(payload['thresholds'][name],4))
    for present in (True,False):
        s=[r for r in records if r['query_genus_in_gallery']==present]
        print('  genus present',present,'accepted',sum(r[name]['accepted'] for r in s),'/',len(s),
              'correct accepted',sum(r[name]['accepted'] and r['query']['genus']==r[name]['neighbor_genus'] for r in s))
