"""Stress closed-set retrieval by synthetically hiding either long-axis half of a query."""
import csv
import hashlib
import json
from pathlib import Path

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

ROOT=Path(__file__).resolve().parent.parent
SOURCE=ROOT/'results/r14/prefix';OUT=ROOT/'results/l22'
replay=json.loads((ROOT/'results/l9/prefix-gallery-replay.json').read_text())
gallery=replay['initial_gallery'];queries=[r['query'] for r in replay['queries']]
ids={r['annotation_id'] for r in queries};metadata={}
with Path('/tmp/ude-metadata.csv').open(newline='',encoding='utf-8-sig') as f:
    for row in csv.DictReader(f):
        if row['annotation_id'] in ids:metadata[row['annotation_id']]=row
assert set(metadata)==ids
queries=[r for r in queries if metadata[r['annotation_id']]['shape']=='Rectangle']
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 source(row):
    path=SOURCE/row['local_file']
    if hashlib.sha256(path.read_bytes()).hexdigest()!=row['sha256']:raise ValueError('Image hash mismatch')
    return Image.open(path).convert('L')

def prepare(image):
    image=image.copy();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 embedding(image):
    a=np.asarray(prepare(image).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()

vectors={r['annotation_id']:embedding(source(r)) for r in gallery}
def ranked(image):
    v=embedding(image)
    scores=sorted(((float(v@vectors[g['annotation_id']]),g) for g in gallery),key=lambda x:-x[0])
    score,g=scores[0];return {'annotation_id':g['annotation_id'],'genus':g['genus'],'score':score}

font=ImageFont.truetype('DejaVuSans.ttf',14);plate=Image.new('RGB',(1380,len(queries)*190),'#f8f8f2');draw=ImageDraw.Draw(plate)
records=[];by_id={r['annotation_id']:r for r in gallery}
for i,q in enumerate(queries):
    im=source(q);row=metadata[q['annotation_id']]
    pts=np.asarray(json.loads(row['points']),dtype=float).reshape(-1,2)-np.array([int(row['bbox_x0']),int(row['bbox_y0'])])
    if pts.shape!=(4,2):raise ValueError('Expected rectangle')
    edge=np.roll(pts,-1,axis=0)-pts;axis=edge[np.argmax(np.linalg.norm(edge,axis=1))];axis/=np.linalg.norm(axis)
    center=pts.mean(axis=0);H,W=im.height,im.width;yy,xx=np.indices((H,W));side=(xx-center[0])*axis[0]+(yy-center[1])*axis[1]
    pixels=np.asarray(im);fill=int(np.median(pixels));a=pixels.copy();b=pixels.copy();a[side>0]=fill;b[side<=0]=fill
    images=[im,Image.fromarray(a),Image.fromarray(b)]
    predictions=[ranked(x) for x in images]
    record={'query':q,'full':predictions[0],'half_a':predictions[1],'half_b':predictions[2]};records.append(record)
    draw.text((8,i*190+4),f"{i+1}. UDE {q['genus']} · annotation {q['annotation_id']}",font=font,fill='#193b36')
    for col,(img,pred,title) in enumerate(zip(images,predictions,['Full query','Half A','Half B'])):
        x=col*460+8;y=i*190+28
        draw.text((x,y),f"{title} → {pred['genus']}",font=font,fill='#193b36')
        # Contrast adjustment is display-only; embeddings use native intensities.
        plate.paste(ImageOps.autocontrast(prepare(img),cutoff=.25).resize((135,135)),(x,y+22))
        plate.paste(ImageOps.autocontrast(prepare(source(by_id[pred['annotation_id']])),cutoff=.25).resize((135,135)),(x+155,y+22))
plate.save(OUT/'partial-retrieval.jpg',quality=90)
(OUT/'partial-retrieval.json').write_text(json.dumps({'gallery':gallery,'query_count':len(records),'records':records,
 'method':'hide one image half separated by the annotated rectangle center and long axis; replace with image median',
 'warning':'synthetic image truncation, one selected source slide; not real partial or overlap labels'},indent=2))
for name in ('full','half_a','half_b'):
    print(name,'same-genus nearest',sum(r['query']['genus']==r[name]['genus'] for r in records),'/',len(records))
