"""Explore local ResNet feature matching for the existing synthetic half-query test."""
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/l23';OUT.mkdir(exist_ok=True)
prior=json.loads((ROOT/'results/l22/partial-retrieval.json').read_text());gallery=prior['gallery'];queries=[r['query'] for r in prior['records']]
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
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()
encoder=torch.nn.Sequential(model.conv1,model.bn1,model.relu,model.maxpool,model.layer1,model.layer2,model.layer3,model.layer4)
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)
    out=Image.new('L',(224,224),int(np.median(np.asarray(image))));out.paste(image,((224-image.width)//2,(224-image.height)//2));return out

def patch_features(image):
    im=prepare(image);gray=np.asarray(im,dtype=np.float32)/255
    a=np.asarray(im.convert('RGB'),dtype=np.float32)/255
    with torch.inference_mode():
        fmap=encoder(((torch.from_numpy(a).permute(2,0,1)-mean)/std)[None])[0]
        vec=torch.nn.functional.normalize(fmap.flatten(1).T,dim=1).numpy()
    if vec.shape!=(49,512):raise ValueError('Unexpected feature grid')
    variations=np.array([gray[y*32:(y+1)*32,x*32:(x+1)*32].std() for y in range(7) for x in range(7)])
    idx=np.argsort(-variations,kind='stable')[:12]
    return vec[idx],idx.tolist()

references={r['annotation_id']:patch_features(source(r))[0] for r in gallery}
def rank(image):
    query,idx=patch_features(image);scores=[];reverse_scores=[]
    for ref in gallery:
        similarity=query@references[ref['annotation_id']].T
        scores.append((float(similarity.max(axis=1).mean()),ref))
        reverse_scores.append((float(similarity.max(axis=0).mean()),ref))
    score,ref=max(scores,key=lambda x:x[0])
    rev_score,rev_ref=max(reverse_scores,key=lambda x:x[0])
    return ({'annotation_id':ref['annotation_id'],'genus':ref['genus'],'score':score,'selected_patch_indices':idx},
            {'annotation_id':rev_ref['annotation_id'],'genus':rev_ref['genus'],'score':rev_score})

font=ImageFont.truetype('DejaVuSans.ttf',14);sheet=Image.new('RGB',(1500,len(queries)*190),'#f8f8f2');draw=ImageDraw.Draw(sheet)
records=[];by_id={r['annotation_id']:r for r in gallery}
for i,q in enumerate(queries):
    image=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'])])
    edges=np.roll(pts,-1,axis=0)-pts;axis=edges[np.argmax(np.linalg.norm(edges,axis=1))];axis/=np.linalg.norm(axis)
    center=pts.mean(axis=0);yy,xx=np.indices((image.height,image.width));side=(xx-center[0])*axis[0]+(yy-center[1])*axis[1]
    pixels=np.asarray(image);fill=int(np.median(pixels));a=pixels.copy();b=pixels.copy();a[side>0]=fill;b[side<=0]=fill
    halves=[Image.fromarray(a),Image.fromarray(b)];original=prior['records'][i]
    assert original['query']['annotation_id']==q['annotation_id']
    blank_forward,blank_reverse=rank(Image.new('L',image.size,fill))
    result={'query':q,'conditions':{},'background_only':{'patch':blank_forward,'reverse_patch':blank_reverse}}
    for key,im in zip(('half_a','half_b'),halves):
        forward,reverse=rank(im)
        result['conditions'][key]={'global':original[key],'patch':forward,'reverse_patch':reverse}
    records.append(result)
    draw.text((8,i*190+4),f"{i+1}. Public reference genus {q['genus']} · {q['annotation_id']}",font=font,fill='#193b36')
    views=[]
    for key,im in zip(('half_a','half_b'),halves):
        res=result['conditions'][key]
        views.extend([(im,key.replace('_',' ').upper()),(source(by_id[res['global']['annotation_id']]),'Global: '+res['global']['genus']),
                      (source(by_id[res['patch']['annotation_id']]),'Patch: '+res['patch']['genus'])])
    for j,(im,title) in enumerate(views):
        x=j*250+8;y=i*190+27;draw.text((x,y),title,font=font,fill='#193b36')
        sheet.paste(ImageOps.autocontrast(prepare(im),cutoff=.25).resize((140,140)),(x,y+23))
sheet.save(OUT/'patch-retrieval.jpg',quality=90)
(OUT/'patch-retrieval.json').write_text(json.dumps({'description':'12 highest-contrast 32x32 display-grid patches; ResNet-18 layer4 7x7 local vectors, directional mean of best matches',
 'warning':'Patch features have large receptive fields; texture selection can prefer debris or background.', 'records':records},indent=2))
for key in ('half_a','half_b'):
    for name in ('global','patch','reverse_patch'):
        print(key,name,sum(r['conditions'][key][name]['genus']==r['query']['genus'] for r in records),'/',len(records))
print('blank query nearest genera', {g:sum(r['background_only']['patch']['genus']==g for r in records) for g in sorted({r['background_only']['patch']['genus'] for r in records})})
