"""Compare synthetic overlap compositing with source crops and a real microscope background."""
import json
import sys
import time
from pathlib import Path

import cv2
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

torch.set_num_threads(4)
root=Path(__file__).resolve().parent.parent
sys.path.insert(0,str(root/"experiments"))
from scan_fields import Stack

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()
fields=json.loads((root/"results/diatom-practice-round1.json").read_text())["fields"]
source=next(x for x in fields if x["slide"].startswith("GC104890a_") and x["field"]==8)
background=next(x for x in fields if x["slide"].startswith("GC105196a_") and x["field"]==8)
with Stack(root/"scans"/source["slide"]) as s:
 src=np.asarray(s.field(0,*source["origin_xy"],768),dtype=np.float32)
with Stack(root/"scans"/background["slide"]) as s:
 base=np.asarray(s.field(0,background["origin_xy"][0]+128,background["origin_xy"][1]+128,512),dtype=np.float32)
objects=[]
for index in (2,3):
 mask=np.asarray(Image.open(root/f"results/r6/mask-{index}.png").convert("L"))>0
 ys,xs=np.where(mask)
 x0,x1=max(0,xs.min()-10),min(768,xs.max()+11)
 y0,y1=max(0,ys.min()-10),min(768,ys.max()+11)
 crop=src[y0:y1,x0:x1]
 cropped=mask[y0:y1,x0:x1]
 surroundings=crop[~cropped]
 # The collar gives a local illumination reference, not a physical optical calibration.
 bg=float(np.median(surroundings)) if surroundings.size else float(np.median(src))
 objects.append((crop,cropped,bg))
cases=[("separate","opaque",((150,160),(350,350))),("crossing","opaque",((245,250),(255,250))),
       ("separate","multiply",((150,160),(350,350))),("crossing","multiply",((245,250),(255,250)))]
plate=Image.new("RGB",(1200,1260),"#f8f8f2")
d=ImageDraw.Draw(plate)
font=ImageFont.truetype("DejaVuSans.ttf",17)
records=[]
out=root/"results/l4";out.mkdir(exist_ok=True)
for i,(layout,method,centers) in enumerate(cases):
 result=base.copy(); truth=[]
 for (crop,mask,bg),(cx,cy) in zip(objects,centers):
  h,w=crop.shape; x0=cx-w//2;y0=cy-h//2
  target=result[y0:y0+h,x0:x0+w]
  assert target.shape==crop.shape
  if method=="opaque":target[mask]=crop[mask]
  else:target[mask]*=np.clip(crop[mask]/max(bg,1),0.25,1.5)
  ys,xs=np.where(mask)
  truth.append([int(x0+xs.min()),int(y0+ys.min()),int(x0+xs.max()+1),int(y0+ys.max()+1)])
 img=np.clip(result,0,255).astype(np.uint8)
 pred=model.predict(np.repeat(img[:,:,None],3,axis=2),imgsz=512,conf=.05,device="cpu",verbose=False)[0]
 boxes=pred.boxes.xyxy.cpu().tolist()
 display=ImageOps.autocontrast(Image.fromarray(img),cutoff=.25).convert("RGB")
 dr=ImageDraw.Draw(display)
 for b in truth:dr.rectangle(b,outline="#ffcf38",width=2)
 for b in boxes:dr.rectangle(b,outline="#00b99a",width=2)
 Image.fromarray(img).save(out/f"blend-{i+1}.png")
 x=(i%2)*600+10;y=(i//2)*630+35
 plate.paste(display.resize((560,560),Image.Resampling.LANCZOS),(x,y))
 d.text((x,y-25),f"{layout.capitalize()} · {method} · {len(boxes)} model boxes",font=font,fill="#193b36")
 records.append(dict(layout=layout,method=method,truth_boxes=truth,predicted_boxes=boxes,confidences=pred.boxes.conf.cpu().tolist(),
                     background=dict(slide=background["slide"],field=background["field"],plane=0),
                     source=dict(slide=source["slide"],field=source["field"],plane=0),source_bg= [o[2] for o in objects]))
 print(layout,method,len(boxes),flush=True)
plate.save(out/"blending-comparison.jpg",quality=92)
(out/"blending-predictions.json").write_text(json.dumps(records,indent=2))
