"""Add optional, unverified DIAMORPH candidate suggestions to a field bundle."""
import argparse
import csv
import json
from pathlib import Path

import cv2
import numpy as np
import torch
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 TAXA,preprocess
from ingest_review import digest,inside


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--bundle',type=Path,required=True);p.add_argument('--weights',type=Path,required=True)
    p.add_argument('--taxonomy',type=Path,default=TAXA)
    p.add_argument('--alternatives',action='store_true',help='Classify available split, tile, and cross-plane alternatives in a separate manifest')
    a=p.parse_args();b=json.loads((a.bundle/'bundle.json').read_text())
    out=a.bundle/('classifier-alternative-suggestions.json' if a.alternatives else 'classifier-suggestions.json')
    if out.exists():raise FileExistsError('Classifier suggestions already exist')
    if a.alternatives and (a.bundle/'classifier-suggestions.json').exists():
        original=json.loads((a.bundle/'classifier-suggestions.json').read_text())
        if original.get('bundle_id')!=b['bundle_id'] or original.get('model_sha256')!=digest(a.weights) or original.get('taxonomy_sha256')!=digest(a.taxonomy):
            raise ValueError('Alternative classifier or taxonomy differs from existing suggestions')
    candidates=b['candidates'];source_manifests={}
    if a.alternatives:
        candidates=[]
        for filename,format_name,key in [('split-alternatives.json','diatom-split-alternatives-v1','hypotheses'),
                                         ('tile-proposals.json','diatom-tile-proposals-v1','proposals'),
                                         ('stack-proposals.json','diatom-stack-proposals-v1','proposals')]:
            path=a.bundle/filename
            if not path.exists():continue
            data=json.loads(path.read_text())
            if data.get('format')!=format_name or data.get('bundle_id')!=b['bundle_id'] or not isinstance(data.get(key),list):
                raise ValueError(f'Invalid {filename}')
            source_manifests[filename]=digest(path);candidates.extend(data[key])
        if not candidates:raise ValueError('No split, tile, or cross-plane alternatives found')
        ids=[c['id'] for c in b['candidates']]+[c['id'] for c in candidates]
        if len(ids)!=len(set(ids)):raise ValueError('Duplicate candidate IDs')
    taxa={r['taxonomic_code']:r for r in csv.DictReader(a.taxonomy.open(),delimiter=';')}
    allowed=[ClassificationModel,Conv,C2f,Bottleneck,Classify,Sequential,Conv2d,BatchNorm2d,SiLU,
             ModuleList,AdaptiveAvgPool2d,Linear,Dropout,Compose,CenterCrop,Resize,ToTensor,Normalize,InterpolationMode]
    torch.set_num_threads(4)
    with torch.serialization.safe_globals(allowed):checkpoint=torch.load(a.weights,map_location='cpu',weights_only=True)
    trained=checkpoint['model'].float()
    if any(code not in taxa for code in trained.names.values()):raise ValueError('Unmapped model taxon code')
    model=YOLO('yolov8l-cls.yaml',task='classify');model.model=trained
    scale=b['calibration'];records=[]
    for candidate in candidates:
        path=inside(a.bundle,candidate['crop']);image=cv2.imread(str(path))
        if image is None:raise ValueError('Cannot read candidate image')
        prepared=preprocess(image,scale['x_um_per_pixel'],scale['y_um_per_pixel'])
        result=model.predict(prepared,imgsz=512,device='cpu',verbose=False)[0];scores=result.probs.data.cpu().numpy()
        ranked=[]
        for i in np.argsort(-scores)[:5]:
            code=trained.names[int(i)];taxon=taxa[code]
            ranked.append({'code':code,'genus':taxon['genus'],'species':taxon['species'],
                           'infra_species':taxon['infra_species'],'score':float(scores[int(i)])})
        records.append({'candidate_id':candidate['id'],'source_crop':candidate['crop'],'source_crop_sha256':digest(path),
                        'top_five':ranked})
        print(candidate['id'],ranked[0]['code'],flush=True)
    output={'format':'diatom-classifier-suggestions-v1','bundle_id':b['bundle_id'],
            'model':'DIAMORPH species v2','model_sha256':digest(a.weights),'taxonomy_sha256':digest(a.taxonomy),
            'model_class_count':len(trained.names),'preprocessing':'DIAMORPH square-pad order, 0.1 µm/pixel, 512 × 512',
            'source_manifests_sha256':source_manifests,
            'warning':'Closed-set provisional model outputs; scores are not calibrated probabilities and names are not identifications.',
            'records':records}
    out.write_text(json.dumps(output,indent=2)+'\n')


if __name__=='__main__':main()
