"""Evaluate DIAMORPH on already-inspected UDE cutouts with known source scale."""
import collections
import csv
import hashlib
import json
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image,ImageDraw,ImageFont
from torchvision.transforms import Compose,CenterCrop,Resize,ToTensor,Normalize,InterpolationMode
from ultralytics import YOLO
from ultralytics.nn.tasks import ClassificationModel
from ultralytics.nn.modules import Conv,C2f,Bottleneck,Classify
from torch.nn import Sequential,Conv2d,BatchNorm2d,SiLU,ModuleList,AdaptiveAvgPool2d,Linear,Dropout

from diamorph_preview import WEIGHTS,TAXA,preprocess

ROOT=Path(__file__).resolve().parent.parent
OUT=ROOT/'results/pilot/diamorph-ude-diagnostic'
INVALID={'none','nan','null','unknown','unidentified','n/a',''}


def normalized(value):
    return value.strip().casefold() if isinstance(value,str) and value.strip().casefold() not in INVALID else None


def main():
    torch.set_num_threads(4)
    allow=[ClassificationModel,Conv,C2f,Bottleneck,Classify,Sequential,Conv2d,BatchNorm2d,SiLU,
           ModuleList,AdaptiveAvgPool2d,Linear,Dropout,Compose,CenterCrop,Resize,ToTensor,Normalize,InterpolationMode]
    with torch.serialization.safe_globals(allow):checkpoint=torch.load(WEIGHTS,map_location='cpu',weights_only=True)
    trained=checkpoint['model'].float();model=YOLO('yolov8l-cls.yaml',task='classify');model.model=trained
    taxa={r['taxonomic_code']:r for r in csv.DictReader(TAXA.open(),delimiter=';')}
    if any(v not in taxa for v in trained.names.values()):raise ValueError('Unmapped DIAMORPH code')
    species={normalized(taxa[code]['species']) for code in trained.names.values()}
    genera={normalized(taxa[code]['genus']) for code in trained.names.values()}
    manifests=[(ROOT/'results/r7/reference-manifest.json','gallery_subset'),(ROOT/'results/r14/prefix/reference-manifest.json','single_slide_prefix')]
    selected=[]
    for path,group in manifests:
        raw=json.loads(path.read_text());rows=raw if isinstance(raw,list) else raw['rows']
        selected.extend((dict(row),path.parent,group) for row in rows)
    records=[]
    for index,(row,base,group) in enumerate(selected,1):
        path=base/row['local_file'];image=cv2.imread(str(path))
        if image is None:raise ValueError(f'Unreadable source image: {path}')
        h,w=image.shape[:2];scale=.09
        rec={'group':group,'source_slide':row['source_slide'],'annotation_id':row['annotation_id'],
             'image':str(path.relative_to(ROOT)),'source_species':row.get('species'), 'source_genus':row.get('genus'),
             'source_species_known_exact':normalized(row.get('species')) in species if normalized(row.get('species')) else None,
             'source_genus_known_exact':normalized(row.get('genus')) in genera if normalized(row.get('genus')) else None,
             'center_crop_required':max(round(w*(scale/.1)),round(h*(scale/.1)))>512}
        try:prepared=preprocess(image,scale,scale)
        except (cv2.error,ValueError) as exc:
            rec.update(status='preprocess_error',error=str(exc));records.append(rec);continue
        result=model.predict(prepared,imgsz=512,device='cpu',verbose=False)[0]
        probs=result.probs.data.cpu().numpy();rank=np.argsort(-probs)[:5]
        rec['top_five']=[{'code':trained.names[int(i)],'species':taxa[trained.names[int(i)]]['species'],
             'genus':taxa[trained.names[int(i)]]['genus'],'score':float(probs[int(i)])} for i in rank]
        rec['status']='ok';records.append(rec)
        if index%10==0:print(f'Processed {index}/{len(selected)}',flush=True)
    summary={}
    for group in ('gallery_subset','single_slide_prefix','combined'):
        subset=[r for r in records if group=='combined' or r['group']==group]
        valid_species=[r for r in subset if normalized(r['source_species'])]
        valid_genus=[r for r in subset if normalized(r['source_genus'])]
        known=[r for r in valid_species if r['source_species_known_exact']]
        def hit(r,key,n):
            return r['status']=='ok' and normalized(r['source_'+key]) in [normalized(q[key]) for q in r['top_five'][:n]]
        summary[group]={'images':len(subset),'preprocessing_errors':sum(r['status']!='ok' for r in subset),
            'genus_labeled':len(valid_genus),'genus_top1_exact':sum(hit(r,'genus',1) for r in valid_genus),
            'species_labeled':len(valid_species),'species_top1_exact':sum(hit(r,'species',1) for r in valid_species),
            'species_top5_exact':sum(hit(r,'species',5) for r in valid_species),
            'known_species_labeled':len(known),'known_species_top1_exact':sum(hit(r,'species',1) for r in known),
            'known_species_top5_exact':sum(hit(r,'species',5) for r in known),
            'taxa_absent_species_exact':sum(r['source_species_known_exact'] is False for r in valid_species),
            'center_crop_required':sum(r['center_crop_required'] for r in subset)}
    OUT.mkdir(parents=True,exist_ok=True)
    (OUT/'diagnostic.json').write_text(json.dumps({'source_scale_um_per_pixel':.09,
        'model_sha256':hashlib.sha256(WEIGHTS.read_bytes()).hexdigest(),'summary':summary,'records':records},indent=2)+'\n')
    # Fixed first three examples per group, not chosen by correctness.
    examples=[r for group in ('gallery_subset','single_slide_prefix') for r in [x for x in records if x['group']==group][:3]]
    font=ImageFont.truetype('DejaVuSans.ttf',15);sheet=Image.new('RGB',(1050,len(examples)*190),'#f8f8f2');draw=ImageDraw.Draw(sheet)
    for i,row in enumerate(examples):
        y=i*190;image=Image.open(ROOT/row['image']).convert('RGB');image.thumbnail((260,150));sheet.paste(image,(8,y+28))
        draw.text((8,y+3),row['group']+' · '+str(row['annotation_id']),font=font,fill='#193b36')
        draw.text((300,y+10),'Dataset label: '+str(row['source_species']),font=font,fill='#193b36')
        if row['status']=='ok':
            draw.text((300,y+40),'Model top 1: '+row['top_five'][0]['species'],font=font,fill='#193b36')
            draw.text((300,y+70),'Exact species in vocabulary: '+str(row['source_species_known_exact']),font=font,fill='#193b36')
        else:draw.text((300,y+40),'Preprocessing failed',font=font,fill='#a14141')
    sheet.save(OUT/'examples.jpg',quality=90)
    print(json.dumps(summary,indent=2),flush=True)


if __name__=='__main__':main()
