"""Audit the pilot's species retrieval with slide-held-out public cutouts.

Development diagnostic only: small nonrandom public subsets; no Academy truth.
"""
import hashlib
import json
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

from run_field import embedding

ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT/'results/pilot/species-evaluation'
WEIGHTS = Path('/tmp/resnet18-f37072fd.pth')
GALLERY_MANIFEST = ROOT/'results/r7/reference-manifest.json'
UNKNOWN_MANIFEST = ROOT/'results/r14/prefix/reference-manifest.json'
INVALID = {'none','nan','null','unknown','unidentified','n/a',''}


def valid_species(row):
    return isinstance(row.get('species'), str) and row['species'].strip().casefold() not in INVALID


def evaluate(query, candidates):
    # Match the prototype's maximum-reference-per-species ranking.
    similarities = sorted(((float(np.dot(query['vector'], r['vector'])), r) for r in candidates),
                          key=lambda pair: -pair[0])
    suggestions=[];seen=set()
    for score,reference in similarities:
        if reference['species'] in seen:continue
        seen.add(reference['species'])
        suggestions.append({'species':reference['species'],'genus':reference['genus'],
                            'score':score,'reference_annotation_id':reference['annotation_id'],
                            'reference_file':str(reference['path'].relative_to(ROOT))})
        if len(suggestions)==3:break
    return {'query_annotation_id':query['annotation_id'], 'query_species':query['species'],
            'query_genus':query['genus'], 'query_slide':query['source_slide'],
            'query_file':str(query['path'].relative_to(ROOT)),
            'known_species':query['species'] in {r['species'] for r in candidates},
            'known_genus':query['genus'] in {r['genus'] for r in candidates}, 'suggestions':suggestions}


def main():
    torch.set_num_threads(4)
    model=resnet18(weights=None)
    model.load_state_dict(torch.load(WEIGHTS,map_location='cpu',weights_only=True))
    model.fc=torch.nn.Identity();model.eval()
    gallery_raw=json.loads(GALLERY_MANIFEST.read_text())
    gallery=[dict(r,path=GALLERY_MANIFEST.parent/r['local_file']) for r in gallery_raw
             if r.get('split')=='gallery' and valid_species(r)]
    unknown_raw=json.loads(UNKNOWN_MANIFEST.read_text())['rows']
    queries=[dict(r,path=UNKNOWN_MANIFEST.parent/r['local_file']) for r in unknown_raw if valid_species(r)]
    for row in gallery+queries:
        with Image.open(row['path']) as image: row['vector']=embedding(model,image)
    heldout=[evaluate(q,[r for r in gallery if r['source_slide']!=q['source_slide']]) for q in gallery]
    unknown=[evaluate(q,gallery) for q in queries]
    if {q['query_slide'] for q in unknown}&{g['source_slide'] for g in gallery}:
        raise ValueError('Filename-derived source slides overlap')
    known=[r for r in heldout if r['known_species']]
    summary={'gallery_images':len(gallery),'gallery_species':len({r['species'] for r in gallery}),
             'heldout_gallery_queries':len(heldout),'heldout_species_known':len(known),
             'heldout_species_top1':sum(r['query_species']==r['suggestions'][0]['species'] for r in known),
             'heldout_species_top3':sum(any(r['query_species']==s['species'] for s in r['suggestions']) for r in known),
             'heldout_genus_known':sum(r['known_genus'] for r in heldout),
             'heldout_genus_top1':sum(r['known_genus'] and r['query_genus']==r['suggestions'][0]['genus'] for r in heldout),
             'external_labeled_queries':len(unknown),
             'external_species_absent':sum(not r['known_species'] for r in unknown),
             'external_genus_absent':sum(not r['known_genus'] for r in unknown),
             'external_forced_suggestions':sum(bool(r['suggestions']) for r in unknown)}
    OUT.mkdir(parents=True,exist_ok=True)
    data={'scope':'development only; source-slide separation is not proven biological-sample separation',
          'encoder_sha256':hashlib.sha256(WEIGHTS.read_bytes()).hexdigest(),
          'summary':summary,'slide_held_out_gallery':heldout,'external_queries':unknown}
    (OUT/'evaluation.json').write_text(json.dumps(data,indent=2)+'\n')
    # Fixed first cases illustrate suggestions, without using correctness to select.
    examples=heldout[:3]+unknown[:3]
    font=ImageFont.truetype('DejaVuSans.ttf',15)
    plate=Image.new('RGB',(1000, len(examples)*235),'#f8f8f2');draw=ImageDraw.Draw(plate)
    for i,row in enumerate(examples):
        for j,(file,title,subtitle) in enumerate([
            (row['query_file'],'Reference-labeled query',row['query_species']),
            (row['suggestions'][0]['reference_file'],'Nearest gallery image',row['suggestions'][0]['species'])]):
            image=Image.open(ROOT/file).convert('RGB');image.thumbnail((455,165),Image.Resampling.LANCZOS)
            x=j*500+10;y=i*235
            draw.text((x,y+2),title,font=font,fill='#193b36');draw.text((x,y+23),subtitle,font=font,fill='#193b36')
            plate.paste(image,(x,y+48))
    plate.save(OUT/'examples.jpg',quality=90)
    print(json.dumps(summary,indent=2),flush=True)


if __name__=='__main__':main()
