"""Replay an oracle-updated same-slide gallery from the recovered UDE prefix."""
import hashlib
import json
import random
from collections import Counter
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
SOURCE=ROOT/'results/r14/prefix';OUT=ROOT/'results/l9'
data=json.loads((SOURCE/'reference-manifest.json').read_text())['rows']
counts=Counter(r['genus'] for r in data)
genera=sorted(k for k,v in counts.items() if v>=3)
rows=[r for r in data if r['genus'] in genera]
assert len({r['source_slide'] for r in rows})==1
seed=20261201;rng=random.Random(seed);rng.shuffle(rows)
# Select one initial reference per included genus. This is an oracle-seeded setup,
# and the order after seeding is random, not actual microscope traversal order.
first={}
for r in rows:
    if r['genus'] not in first:first[r['genus']]=r
initial=list(first.values());initial_ids={r['annotation_id'] for r in initial}
queries=[r for r in rows if r['annotation_id'] not in initial_ids]
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):
    p=SOURCE/row['local_file']
    if hashlib.sha256(p.read_bytes()).hexdigest()!=row['sha256']:raise ValueError('Image hash mismatch')
    im=Image.open(p).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(row):
    a=np.asarray(prepare(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()

features={r['annotation_id']:feature(r) for r in rows}
def nearest(q,gallery):
    v=features[q['annotation_id']]
    ordered=sorted(((float(v@features[r['annotation_id']]),r) for r in gallery),key=lambda x:-x[0])
    score,match=ordered[0]
    return {'annotation_id':match['annotation_id'],'genus':match['genus'],'score':score}

growing=initial.copy();records=[]
for position,q in enumerate(queries,1):
    fixed=nearest(q,initial);adaptive=nearest(q,growing)
    records.append({'position':position,'query':q,'gallery_size':len(growing),'fixed':fixed,'growing':adaptive})
    # Reveal the public dataset label only after both predictions.
    growing.append(q)
assert all(r['query']['annotation_id']!=r[name]['annotation_id'] for r in records for name in ('fixed','growing'))
payload={'seed':seed,'included_genera':genera,'initial_gallery':initial,'queries':records,
         'warning':'One cached slide; dataset labels are used as oracle confirmations; shuffled order is not a real transect.'}
(OUT/'prefix-gallery-replay.json').write_text(json.dumps(payload,indent=2))
font=ImageFont.truetype('DejaVuSans.ttf',15);plate=Image.new('RGB',(1100,len(records)*180),'#f8f8f2');draw=ImageDraw.Draw(plate)
by_id={r['annotation_id']:r for r in rows}
for i,rec in enumerate(records):
    y=i*180;q=rec['query'];draw.text((8,y+3),f"{rec['position']}. Query: {q['genus']} · ID {q['annotation_id']}",font=font,fill='#193b36')
    views=[(q,'Query'),(by_id[rec['fixed']['annotation_id']],'Fixed · '+rec['fixed']['genus']),
           (by_id[rec['growing']['annotation_id']],'Growing · '+rec['growing']['genus'])]
    for j,(row,title) in enumerate(views):
        x=j*360+8;draw.text((x,y+25),title,font=font,fill='#193b36');plate.paste(prepare(row).resize((130,130)),(x,y+45))
plate.save(OUT/'prefix-gallery-replay.jpg',quality=90)
for name in ('fixed','growing'):
    print(name,'genus matches',sum(r['query']['genus']==r[name]['genus'] for r in records),'/',len(records))
print('genera',genera,'initial',len(initial),'queries',len(queries),'neighbor changed',sum(r['fixed']['annotation_id']!=r['growing']['annotation_id'] for r in records))
