"""Add optional multi-plane detector track hypotheses to a review bundle."""
import argparse
import json
import math
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image
from torchvision.models import resnet18
from ultralytics import SAM, YOLO
from ultralytics.nn.tasks import DetectionModel
from ultralytics.nn.modules import Conv,C2f,Bottleneck,SPPF,Concat,Detect,DFL
from torch.nn import Sequential,Conv2d,BatchNorm2d,SiLU,ModuleList,Identity,MaxPool2d,Upsample

from run_field import embedding,sha256

ROOT=Path(__file__).resolve().parent.parent
DETECTOR_SHA='66b9b2a3f57e92e7062638a27c1212612c60776df8686b49e018ea3ac96a82df'


def box_iou(a,b):
    w=max(0,min(a[2],b[2])-max(a[0],b[0]));h=max(0,min(a[3],b[3])-max(a[1],b[1]))
    intersection=w*h;union=(a[2]-a[0])*(a[3]-a[1])+(b[2]-b[0])*(b[3]-b[1])-intersection
    return intersection/union if union>0 else 0


def link_planes(plane_rows,threshold,max_gap):
    """Greedy one-to-one box linking; tracks remain unverified hypotheses."""
    tracks=[]
    for z,boxes in sorted(plane_rows):
        pairs=[]
        for ti,track in enumerate(tracks):
            last=track['observations'][-1]
            if 0<z-last['z']<=max_gap:
                for bi,box in enumerate(boxes):
                    score=box_iou(last['box'],box['box'])
                    if score>=threshold:pairs.append((-score,ti,bi))
        used_tracks=set();used_boxes=set()
        for _,ti,bi in sorted(pairs):
            if ti in used_tracks or bi in used_boxes:continue
            tracks[ti]['observations'].append(boxes[bi]);used_tracks.add(ti);used_boxes.add(bi)
        for bi,box in enumerate(boxes):
            if bi not in used_boxes:tracks.append({'observations':[box]})
    for track in tracks:track['representative']=max(track['observations'],key=lambda x:x['confidence'])
    return tracks


def detect_tracks(root,b,focus,detector_path,threshold,max_gap):
    if sha256(detector_path)!=b['models']['detector_sha256']:raise ValueError('Detector does not match bundle')
    allowed=[DetectionModel,Conv,C2f,Bottleneck,SPPF,Concat,Detect,DFL,
             Sequential,Conv2d,BatchNorm2d,SiLU,ModuleList,Identity,MaxPool2d,Upsample,set]
    with torch.serialization.safe_globals(allowed):checkpoint=torch.load(detector_path,map_location='cpu',weights_only=True)
    detector=YOLO('yolov8n.yaml',task='detect');detector.model=checkpoint['model'].float()
    plane_rows=[];counts=[]
    for plane in sorted(focus['planes'],key=lambda x:x['z']):
        path=root/plane['image']
        if sha256(path)!=plane['sha256']:raise ValueError('Focus plane hash mismatch')
        with Image.open(path) as im:
            image=im.convert('RGB')
            if image.size!=(b['size'],b['size']):raise ValueError('Focus plane size mismatch')
            result=detector.predict(np.asarray(image),imgsz=768,conf=b['detector_confidence'],device='cpu',verbose=False)[0]
        boxes=result.boxes.xyxy.cpu().tolist();scores=result.boxes.conf.cpu().tolist()
        selected=[{'z':plane['z'],'box':box,'confidence':score} for box,score in list(zip(boxes,scores))[:b['max_candidates']]]
        plane_rows.append((plane['z'],selected));counts.append({'z':plane['z'],'detected_before_limit':len(boxes),'used':len(selected)})
        print(f'Z {plane["z"]}: {len(selected)} proposals ({len(boxes)} before limit)',flush=True)
    return link_planes(plane_rows,threshold,max_gap),counts


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--bundle',type=Path,required=True);p.add_argument('--segmenter',type=Path,required=True)
    p.add_argument('--encoder',type=Path,required=True);p.add_argument('--gallery',type=Path,required=True)
    p.add_argument('--detector',type=Path,help='Run the bundle detector on each focal plane; omit to use the existing R5 field tracks')
    p.add_argument('--link-iou',type=float,default=.3);p.add_argument('--max-z-gap',type=int,default=1)
    args=p.parse_args();root=args.bundle;b=json.loads((root/'bundle.json').read_text())
    if not 0<args.link_iou<=1 or args.max_z_gap<1:p.error('link-iou must be in (0, 1] and max-z-gap positive')
    for path,key in ((args.segmenter,'segmenter_sha256'),(args.encoder,'encoder_sha256'),(args.gallery,'gallery_manifest_sha256')):
        if sha256(path)!=b['models'][key]:raise ValueError(f'{key} does not match bundle')
    out=root/'stack-proposals.json'
    if out.exists():raise FileExistsError('Stack proposals already exist')
    focus=json.loads((root/'focus-planes.json').read_text())
    if focus['bundle_id']!=b['bundle_id']:raise ValueError('Focus bundle mismatch')
    planes={x['z']:x for x in focus['planes']}
    torch.set_num_threads(4)
    if args.detector:
        tracks,counts=detect_tracks(root,b,focus,args.detector,args.link_iou,args.max_z_gap)
        source_description='Detector run on each saved focal plane; greedy one-to-one box links, highest-confidence observation per track'
        link_iou,max_z_gap=args.link_iou,args.max_z_gap
    else:
        if b['models']['detector_sha256']!=DETECTOR_SHA:raise ValueError('Bundle detector differs from recorded R5 detector')
        fields=json.loads((ROOT/'results/diatom-practice-round1.json').read_text())['fields']
        selected=[f for f in fields if f['slide']==b['slide'] and f['origin_xy']==b['origin_xy']]
        if len(selected)!=1:raise ValueError('Existing R5 proposals only support one matching practice field; supply --detector')
        linked=json.loads((ROOT/'results/r5/linked-proposals.json').read_text())
        matches=[r for r in linked['fields'] if r['slide']==b['slide'] and r['field']==selected[0]['field']]
        if len(matches)!=1 or matches[0]['initial_z']!=b['z']:raise ValueError('R5 field or original focal plane mismatch')
        tracks=matches[0]['tracks'];counts=None;source_description='R5 greedy linked detector tracks, highest-confidence observation per track'
        link_iou,max_z_gap=linked['iou_threshold'],linked['maximum_z_gap']
    rows=json.loads(args.gallery.read_text());rows=rows if isinstance(rows,list) else rows['rows']
    invalid={'none','nan','null','unknown','unidentified','n/a',''}
    rows=[r for r in rows if isinstance(r.get('species'),str) and r['species'].strip().casefold() not in invalid
          and r.get('local_file') and (not r.get('split') or r['split']=='gallery')]
    torch.set_num_threads(4);encoder=resnet18(weights=None)
    encoder.load_state_dict(torch.load(args.encoder,map_location='cpu',weights_only=True));encoder.fc=torch.nn.Identity();encoder.eval()
    references=[]
    for i,row in enumerate(rows,1):
        source=args.gallery.parent/row['local_file'];copy=root/f'references/{i:04d}.png'
        with Image.open(source) as original,Image.open(copy) as local:
            if original.size!=local.size or original.convert('RGB').tobytes()!=local.convert('RGB').tobytes():raise ValueError('Gallery image mismatch')
            vector=embedding(encoder,local)
        references.append({'species':row['species'],'source_slide':row.get('source_slide'),
            'annotation_id':row.get('annotation_id'),'image':f'references/{i:04d}.png','source_sha256':sha256(source),'vector':vector})
    segmenter=SAM(str(args.segmenter));target=root/'stack';target.mkdir(exist_ok=False)
    proposals=[]
    for index,track in enumerate(tracks,1):
        rep=track['representative'];z=rep['z'];plane=planes[z];path=root/plane['image']
        if sha256(path)!=plane['sha256']:raise ValueError('Focus plane hash mismatch')
        source=Image.open(path).convert('RGB');image=cv2.cvtColor(np.asarray(source),cv2.COLOR_RGB2BGR)
        if source.size!=(b['size'],b['size']):raise ValueError('Focus plane size mismatch')
        x0,y0,x1,y1=rep['box'];box=(max(0,math.floor(x0)),max(0,math.floor(y0)),min(b['size'],math.ceil(x1)),min(b['size'],math.ceil(y1)))
        if box[0]>=box[2] or box[1]>=box[3]:raise ValueError('Invalid R5 representative box')
        result=segmenter.predict(image,bboxes=rep['box'],imgsz=768,device='cpu',retina_masks=True,verbose=False)[0]
        mask_file=None
        if result.masks is not None and len(result.masks.data)==1:
            mask=result.masks.data[0].cpu().numpy().astype(bool)
            if mask.shape!=(b['size'],b['size']):raise ValueError('Unexpected mask size')
            mask_file=f'stack/track-{index:03d}-mask.png';Image.fromarray(mask.astype('uint8')*255).save(root/mask_file)
        crop=source.crop(box);crop_file=f'stack/track-{index:03d}-crop.png';crop.save(root/crop_file);vector=embedding(encoder,crop)
        ranked=sorted(((float(np.dot(vector,r['vector'])),r) for r in references),key=lambda x:-x[0]);suggestions=[];seen=set()
        for score,ref in ranked:
            if ref['species'] in seen:continue
            seen.add(ref['species']);suggestions.append({k:v for k,v in ref.items() if k!='vector'}|{'similarity':score})
            if len(suggestions)==3:break
        proposals.append({'id':f'stack-{index:03d}','source':'stack_track','plane_z':z,'box':rep['box'],
                          'detector_score':rep['confidence'],'mask':mask_file,'crop':crop_file,'suggestions':suggestions,
                          'observations':track['observations'],'classification':'unresolved'})
        print(f'{index}/{len(tracks)} stack hypotheses',flush=True)
    out.write_text(json.dumps({'format':'diatom-stack-proposals-v1','bundle_id':b['bundle_id'],
        'source':source_description,'link_iou':link_iou,'max_z_gap':max_z_gap,'plane_counts':counts,'proposals':proposals},indent=2)+'\n')


if __name__=='__main__':main()
