"""Evaluate a small slide-separated UDE gallery using ImageNet ResNet-18 features."""
import json
import time
from pathlib import Path

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

torch.set_num_threads(4)
root=Path(__file__).resolve().parent.parent
out=root/"results/r7"
rows=json.loads((out/"reference-manifest.json").read_text())
model=resnet18(weights=None)
state=torch.load("/tmp/resnet18-f37072fd.pth",map_location="cpu",weights_only=True)
model.load_state_dict(state)
model.fc=torch.nn.Identity()
model.eval()
mean=torch.tensor([0.485,0.456,0.406]).view(3,1,1)
std=torch.tensor([0.229,0.224,0.225]).view(3,1,1)
def features(row):
    image=Image.open(out/row["local_file"]).convert("L")
    # Resize each whole cutout without cropping; pad with the median image value.
    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))
    array=np.array(canvas.convert("RGB"),dtype=np.float32)/255
    tensor=(torch.from_numpy(array).permute(2,0,1)-mean)/std
    with torch.inference_mode():
        feature=model(tensor.unsqueeze(0))[0]
        feature=torch.nn.functional.normalize(feature,dim=0)
    return feature.cpu().numpy()
start=time.monotonic()
features_by_id={r["annotation_id"]:features(r) for r in rows}
gallery=[r for r in rows if r["split"]=="gallery"]
queries=[r for r in rows if r["split"]=="query"]
assert not ({r["source_slide"] for r in gallery}&{r["source_slide"] for r in queries})
results=[]
for query in queries:
    scores=[(float(np.dot(features_by_id[query["annotation_id"]],features_by_id[r["annotation_id"]])),r) for r in gallery]
    ranked=sorted(scores,key=lambda x:x[0],reverse=True)[:3]
    results.append(dict(query=query,neighbors=[dict(score=score,**r) for score,r in ranked]))
font=ImageFont.truetype("DejaVuSans.ttf",16)
plate=Image.new("RGB",(1200, len(results)*265),"#f8f8f2")
draw=ImageDraw.Draw(plate)
for i,result in enumerate(results):
    for j,row in enumerate([result["query"]]+result["neighbors"]):
        image=Image.open(out/row["local_file"]).convert("L")
        image.thumbnail((270,190),Image.Resampling.LANCZOS)
        x=j*300+10;y=i*265
        draw.text((x,y+4),("Query" if j==0 else f"Neighbor {j}")+" · "+row["genus"],font=font,fill="#193b36")
        draw.text((x,y+24),f"Annotation {row['annotation_id']}",font=font,fill="#526a63")
        plate.paste(image.convert("RGB"),(x,y+47))
plate.save(out/"ude-nearest-neighbors.jpg",quality=92)
(out/"retrieval-results.json").write_text(json.dumps(results,indent=2))
top1=sum(r["query"]["genus"]==r["neighbors"][0]["genus"] for r in results)
top3=sum(any(r["query"]["genus"]==n["genus"] for n in r["neighbors"]) for r in results)
print("queries",len(results),"top1 genus",top1,"top3 genus",top3,"seconds",round(time.monotonic()-start,2))

# Show local development crops as unlabeled queries against the same external gallery.
import re
import sys
sys.path.insert(0,str(root/"experiments"))
from scan_fields import Stack
traces=json.loads((root/"experiments/visual_traces.json").read_text())
html=(root/"results/field-review.html").read_text()
slides=json.loads(re.search(r'<script type="application/json" id="data">(.*?)</script>',html,re.S)[1])
localdir=out/"local"
localdir.mkdir(exist_ok=True)
local_results=[]
for i,trace in enumerate(traces):
    slide=next(s for s in slides if s["name"].startswith(trace["slide"]+"_"))
    field=slide["fields"][trace["field"]-1]
    with Stack(root/"scans"/slide["name"]) as s:
        image=s.field(field["z"],field["x"],field["y"],768)
    points=trace["points"]
    box=(max(0,min(p[0] for p in points)-8),max(0,min(p[1] for p in points)-8),
         min(768,max(p[0] for p in points)+9),min(768,max(p[1] for p in points)+9))
    crop=image.crop(box)
    path=localdir/f"local-{i+1}.png"
    crop.save(path)
    query=dict(annotation_id=f"local-{i+1}",local_file=f"local/{path.name}",slide=trace["slide"],
               field=trace["field"],z=field["z"],description=trace["description"],box=box)
    v=features(query)
    ranked=sorted(((float(np.dot(v,features_by_id[r["annotation_id"]])),r) for r in gallery),key=lambda x:x[0],reverse=True)[:3]
    local_results.append(dict(query=query,neighbors=[dict(score=score,**r) for score,r in ranked]))
plate=Image.new("RGB",(1200,len(local_results)*265),"#f8f8f2")
draw=ImageDraw.Draw(plate)
for i,result in enumerate(local_results):
    for j,row in enumerate([result["query"]]+result["neighbors"]):
        image=Image.open(out/row["local_file"]).convert("L")
        # Presentation only. Retrieval used native intensities.
        image=ImageOps.autocontrast(image,cutoff=.25)
        image.thumbnail((270,190),Image.Resampling.LANCZOS)
        x=j*300+10;y=i*265
        title=("Academy crop · unverified" if j==0 else f"Reference {j} · "+row["genus"])
        detail=(row["slide"]+" field "+str(row["field"]) if j==0 else "UDE annotation "+row["annotation_id"])
        draw.text((x,y+4),title,font=font,fill="#193b36")
        draw.text((x,y+24),detail,font=font,fill="#526a63")
        plate.paste(image.convert("RGB"),(x,y+47))
plate.save(out/"academy-reference-neighbors.jpg",quality=92)
(out/"academy-neighbors.json").write_text(json.dumps(local_results,indent=2))
print("Academy crops",len(local_results),"no expert taxon labels")
