"""Stress-test DIAMORPH outputs; no human labels or accuracy claims."""
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 BUNDLE,WEIGHTS,TAXA,preprocess

OUT=Path(__file__).resolve().parent.parent/'results/pilot/diamorph-robustness'


def gray_stripe(image):
    out=image.copy();h,w=out.shape[:2];color=int(np.median(out))
    if w>=h:out[:,w*3//8:w*5//8]=color
    else:out[h*3//8:h*5//8,:]=color
    return out


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=';')}
    if any(code not in taxa for code in trained.names.values()):raise ValueError('Unmapped class code')
    b=json.loads((BUNDLE/'bundle.json').read_text());scale=b['calibration'];OUT.mkdir(parents=True,exist_ok=True)
    font=ImageFont.truetype('DejaVuSans.ttf',15);plate=Image.new('RGB',(1200,len(b['candidates'])*210),'#f8f8f2');draw=ImageDraw.Draw(plate)
    variants=('original','rotate90','rotate180','rotate270','gray_stripe')
    records=[]
    for n,c in enumerate(b['candidates'],1):
        source=cv2.imread(str(BUNDLE/c['crop']));transforms=[source,cv2.rotate(source,cv2.ROTATE_90_CLOCKWISE),
            cv2.rotate(source,cv2.ROTATE_180),cv2.rotate(source,cv2.ROTATE_90_COUNTERCLOCKWISE),gray_stripe(source)]
        results=[]
        for j,(name,image) in enumerate(zip(variants,transforms)):
            # A quarter turn exchanges the original X and Y pixel axes.
            sx,sy=scale['x_um_per_pixel'],scale['y_um_per_pixel']
            if name in ('rotate90','rotate270'):sx,sy=sy,sx
            prepared=preprocess(image,sx,sy)
            result=model.predict(prepared,imgsz=512,device='cpu',verbose=False)[0]
            idx=int(result.probs.top1);code=trained.names[idx];meta=taxa[code]
            results.append({'variant':name,'top_code':code,'genus':meta['genus'],'species':meta['species'],
                            'infra_species':meta['infra_species'],'score':float(result.probs.top1conf.cpu())})
            display=Image.fromarray(cv2.cvtColor(image,cv2.COLOR_BGR2RGB));display.thumbnail((218,140),Image.Resampling.LANCZOS)
            x=j*240+8;y=(n-1)*210;draw.text((x,y+4),f'{c["id"]} · {name}',font=font,fill='#193b36')
            plate.paste(display,(x,y+30));draw.text((x,y+175),f'{code} · {results[-1]["score"]:.2f}',font=font,fill='#193b36')
        records.append({'candidate_id':c['id'],'results':results})
        print(c['id'],[(r['variant'],r['top_code'],round(r['score'],3)) for r in results],flush=True)
    data={'bundle_id':b['bundle_id'],'model_sha256':hashlib.sha256(WEIGHTS.read_bytes()).hexdigest(),
          'taxonomy_audit':{'class_codes':len(trained.names),'unique_codes':len(set(trained.names.values())),
             'unique_species_names':len({taxa[c]['species'] for c in trained.names.values()}),
             'unique_full_taxon_names':len({taxa[c]['infra_species'] or taxa[c]['species'] for c in trained.names.values()})},
          'variants':list(variants),'records':records}
    (OUT/'robustness.json').write_text(json.dumps(data,indent=2)+'\n');plate.save(OUT/'robustness.jpg',quality=90)


if __name__=='__main__':main()
