"""Replay three spatially overlapping fields and link box proposals in slide XY."""
import json
import sys
import time
from pathlib import Path

import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont, ImageOps
from ultralytics import 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

ROOT=Path(__file__).resolve().parent.parent
sys.path.insert(0,str(ROOT/'experiments'));sys.path.insert(0,str(ROOT/'research'))
from scan_fields import Stack
from r5_link_planes import link

torch.set_num_threads(4)
allow=[DetectionModel,Conv,C2f,Bottleneck,SPPF,Concat,Detect,DFL,Sequential,Conv2d,BatchNorm2d,SiLU,ModuleList,Identity,MaxPool2d,Upsample,set]
with torch.serialization.safe_globals(allow):
    ckpt=torch.load('/tmp/diatom-detector.pt',map_location='cpu',weights_only=True)
model=YOLO('yolov8n.yaml',task='detect');model.model=ckpt['model'].float()
field=next(f for f in json.loads((ROOT/'results/diatom-practice-round1.json').read_text())['fields'] if f['slide'].startswith('GC108240a_'))
ox,oy=field['origin_xy'];z=2;origins=[(ox-384,oy),(ox,oy),(ox+384,oy)]
records=[];frames=[];started=time.monotonic()
with Stack(ROOT/'scans'/field['slide']) as stack:
    assert min(x for x,y in origins)>=0 and max(x+768 for x,y in origins)<=stack.width and oy+768<=stack.height and z<stack.depth
    for index,(x,y) in enumerate(origins):
        image=stack.field(z,x,y,768)
        pred=model.predict(np.asarray(image.convert('RGB')),imgsz=768,conf=.05,device='cpu',verbose=False)[0]
        boxes=pred.boxes.xyxy.cpu().tolist();conf=pred.boxes.conf.cpu().tolist()
        mapped=[[b[0]+x,b[1]+y,b[2]+x,b[3]+y] for b in boxes]
        records.append({'frame':index,'origin_xy':[x,y],'boxes_local':boxes,'boxes_slide_xy':mapped,'confidences':conf})
        frames.append({'z':index,'boxes':mapped,'confidences':conf})
    # Read an overview from native pixels. Two adjacent tiles cover the full 1536×768 strip.
    strip=Image.new('L',(1536,768));strip.paste(stack.field(z,ox-384,oy,768),(0,0));strip.paste(stack.field(z,ox+384,oy,768),(768,0))
elapsed=time.monotonic()-started
tracks=link(frames)
representatives=[max(track,key=lambda v:v['confidence']) for track in tracks]
output={'slide':field['slide'],'z':z,'frames':records,'tracks':[{'representative':rep,'observations':track} for rep,track in zip(representatives,tracks)],
        'parameters':{'confidence':.05,'link_iou':.5,'maximum_frame_gap':3,'window_size':768,'stride_pixels':384},
        'raw_proposals':sum(len(r['boxes_local']) for r in records),'linked_groups':len(tracks),'elapsed_seconds_including_io':elapsed,
        'pixel_size_um':[stack.sx,stack.sy]}
out=ROOT/'results/r9';out.mkdir(exist_ok=True)
(out/'transect.json').write_text(json.dumps(output,indent=2))
font=ImageFont.truetype('DejaVuSans.ttf',22)
sheet=Image.new('RGB',(1556,2*815),'#f8f8f2');d=ImageDraw.Draw(sheet)
base=ImageOps.autocontrast(strip,cutoff=.25).convert('RGB')
for row in range(2):
    view=base.copy();v=ImageDraw.Draw(view)
    for i,(x,y) in enumerate(origins):v.rectangle((x-(ox-384),0,x-(ox-384)+767,767),outline=['#5d99f3','#f5ce46','#d287fc'][i],width=4)
    if row==0:
        for frame in records:
            for b in frame['boxes_slide_xy']:
                b=[b[0]-(ox-384),b[1]-oy,b[2]-(ox-384),b[3]-oy]
                v.rectangle(b,outline='#00d6ad',width=3)
    else:
        for i,rep in enumerate(representatives):
            b=rep['box'];b=[b[0]-(ox-384),b[1]-oy,b[2]-(ox-384),b[3]-oy]
            v.rectangle(b,outline='#00d6ad',width=3);v.text((b[0]+2,b[1]+2),str(i+1),font=font,fill='#00d6ad')
    sy=row*815+35;sheet.paste(view,(10,sy))
    title=f"All frame detections: {output['raw_proposals']} boxes" if row==0 else f"Linked representatives: {len(tracks)} groups"
    d.text((10,row*815+5),title,font=font,fill='#193b36')
sheet.save(out/'transect.jpg',quality=90)
print('raw',output['raw_proposals'],'tracks',len(tracks),'multi-frame groups',sum(len(t)>1 for t in tracks),'seconds',round(elapsed,2))
