"""Compare fixed, exploratory input preparations on R30's development crops."""
import csv
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
from diamorph_ude_diagnostic import normalized

ROOT=Path(__file__).resolve().parent.parent
OUT=ROOT/'results/pilot/diamorph-input-controls'


def direct_pad(image,fit_full=False):
    """Use the same physical resize, vertical orientation and flip; paste directly."""
    h,w=image.shape[:2]
    image=cv2.resize(image,(max(1,round(w*(.09/.1))),max(1,round(h*(.09/.1)))),interpolation=cv2.INTER_AREA)
    if image.shape[0]<image.shape[1]:image=np.transpose(image,(1,0,2))
    if fit_full and max(image.shape[:2])>512:
        factor=512/max(image.shape[:2]);image=cv2.resize(image,(max(1,round(image.shape[1]*factor)),max(1,round(image.shape[0]*factor))),interpolation=cv2.INTER_AREA)
    y=max(0,(image.shape[0]-512)//2);x=max(0,(image.shape[1]-512)//2)
    image=np.ascontiguousarray(np.flip(image[y:y+512,x:x+512],axis=0))
    h,w=image.shape[:2];canvas=np.full((512,512,3),int(image.mean()),np.uint8)
    y=(512-h)//2;x=(512-w)//2;canvas[y:y+h,x:x+w]=image
    return canvas


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):ckpt=torch.load(WEIGHTS,map_location='cpu',weights_only=True)
    trained=ckpt['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=';')}
    original=json.loads((ROOT/'results/pilot/diamorph-ude-diagnostic/diagnostic.json').read_text())
    import hashlib
    if hashlib.sha256(WEIGHTS.read_bytes()).hexdigest()!=original['model_sha256']:raise ValueError('Checkpoint differs from baseline')
    if any(r['status']!='ok' for r in original['records']):raise ValueError('Baseline contains incomplete records')
    records=[];illustrations=[]
    for idx,row in enumerate(original['records'],1):
        image=cv2.imread(str(ROOT/row['image']))
        if image is None:raise ValueError(f"Missing image {row['image']}")
        author=preprocess(image,.09,.09)
        variants={'direct_mean':direct_pad(image),'fit_full':direct_pad(image,True),'inverted_author':255-author}
        outputs={'author':row['top_five'][0]}
        for name,prepared in variants.items():
            result=model.predict(prepared,imgsz=512,device='cpu',verbose=False)[0]
            code=trained.names[int(result.probs.top1)]
            outputs[name]={'code':code,'genus':taxa[code]['genus'],'species':taxa[code]['species'],
                           'score':float(result.probs.top1conf.cpu())}
        records.append({'annotation_id':row['annotation_id'],'group':row['group'],'image':row['image'],
                        'source_genus':row['source_genus'],'source_species':row['source_species'],
                        'known_species':row['source_species_known_exact'],'center_crop_required':row['center_crop_required'],
                        'predictions':outputs})
        if idx in (1,19):illustrations.append((row,{'author':author,**variants},outputs))
        if idx%10==0:print(f'{idx}/{len(original["records"])} crops',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]
        named_species=[r for r in subset if normalized(r['source_species'])]
        named_genus=[r for r in subset if normalized(r['source_genus'])]
        summary[group]={}
        for variant in ('author','direct_mean','fit_full','inverted_author'):
            summary[group][variant]={'genus_matches':sum(normalized(r['predictions'][variant]['genus'])==normalized(r['source_genus']) for r in named_genus),
                'genus_labeled':len(named_genus),'species_matches':sum(normalized(r['predictions'][variant]['species'])==normalized(r['source_species']) for r in named_species),
                'species_labeled':len(named_species),'top_class_changes_vs_author':sum(r['predictions'][variant]['code']!=r['predictions']['author']['code'] for r in subset)}
    OUT.mkdir(parents=True,exist_ok=True)
    (OUT/'controls.json').write_text(json.dumps({'model_sha256':original['model_sha256'],'records':records,'summary':summary},indent=2)+'\n')
    font=ImageFont.truetype('DejaVuSans.ttf',15);plate=Image.new('RGB',(1100,len(illustrations)*290),'#f8f8f2');draw=ImageDraw.Draw(plate)
    for i,(row,images,outputs) in enumerate(illustrations):
        y=i*290;draw.text((8,y+3),f"{row['group']} · recorded: {row['source_species']}",font=font,fill='#193b36')
        for j,(name,image) in enumerate(images.items()):
            x=j*275+8;display=Image.fromarray(cv2.cvtColor(image,cv2.COLOR_BGR2RGB)).resize((220,220));plate.paste(display,(x,y+30));draw.text((x,y+255),name+' · '+outputs[name]['code'],font=font,fill='#193b36')
    plate.save(OUT/'controls.jpg',quality=90)
    print(json.dumps(summary,indent=2),flush=True)


if __name__=='__main__':main()
