"""Export Ultralytics YOLOv8s (COCO, AGPL-3.0) for the YOLO page.

    python export/export_yolov8.py   ->  web/models/yolov8/

detect.onnx  image [0,1], 640×640 letterboxed → the raw head output at each of the three scales
             (box: 4 edges × 16-bin distance distributions, cls: 80 logits per cell) plus the
             backbone and neck feature maps. Decoding and NMS happen in JavaScript so the page can
             show every step.
grad.onnx    image 640×640, class weights, one spatial mask per scale
             → ∂(Σ mask · class-weighted logits)/∂image, objective
"""
import json

import torch
from ultralytics import YOLO

from common import content_version, CACHE, WEB_MODELS, export_graph, share_weights

OUT = WEB_MODELS / "yolov8"
FEATURES = {2: "b_160", 4: "b_p3", 6: "b_p4", 9: "sppf", 15: "n_p3", 18: "n_p4", 21: "n_p5"}


def run(model, image):
    """The Ultralytics forward loop, keeping every saved feature map; returns (saved, head inputs)."""
    saved, x = {}, image
    for m in model.model[:-1]:
        if m.f != -1:
            x = saved[m.f] if isinstance(m.f, int) else [x if j == -1 else saved[j] for j in m.f]
        x = m(x)
        saved[m.i] = x
    return saved, [saved[i] for i in model.model[-1].f]


def head(model, feats):
    d = model.model[-1]
    return [(d.cv2[i](f), d.cv3[i](f)) for i, f in enumerate(feats)]


def main():
    yolo = YOLO(str(CACHE / "yolov8s.pt"))
    model = yolo.model.fuse().eval().float()
    for p in model.parameters():
        p.requires_grad_(False)
    torch.manual_seed(0)
    img = torch.rand(1, 3, 640, 640)

    def detect(image):
        saved, feats = run(model, image)
        outs = [t for pair in head(model, feats) for t in pair]
        return (*outs, *[saved[i] for i in FEATURES])

    names = [f"{k}_{s}" for s in ("p3", "p4", "p5") for k in ("box", "cls")]
    export_graph(detect, [img], OUT / "detect.onnx", ["image"], names + list(FEATURES.values()))

    def objective(image, class_w, m3, m4, m5):
        _, feats = run(model, image)
        total = 0
        for (_, cls), m in zip(head(model, feats), (m3, m4, m5)):
            total = total + (torch.einsum("k,bkhw->bhw", class_w, cls) * m[:, 0]).sum()
        return total

    def grad(image, class_w, m3, m4, m5):
        return torch.func.grad(objective)(image, class_w, m3, m4, m5), objective(image, class_w, m3, m4, m5)

    cw = torch.zeros(80)
    cw[27] = 1.0  # tie
    masks = [torch.zeros(1, 1, s, s) for s in (80, 40, 20)]
    for m in masks:
        m[0, 0, m.shape[2] // 2, m.shape[3] // 2] = 1.0
    export_graph(grad, [img, cw, *masks], OUT / "grad.onnx", ["image", "class_w", "m3", "m4", "m5"], ["grad", "objective"])

    _, size = share_weights([OUT / "detect.onnx", OUT / "grad.onnx"], "yolov8.bin")
    meta = {"version": content_version(OUT / "yolov8.bin"), "bin": "yolov8.bin", "sizes": {"yolov8.bin": size}, "size": 640, "grad_size": 640,
            "strides": [8, 16, 32], "reg_max": 16, "classes": list(model.names.values()),
            "features": [{"name": n, "layer": i} for i, n in FEATURES.items()]}
    (OUT / "meta.json").write_text(json.dumps(meta))
    print(f"wrote {OUT} ({size / 1e6:.0f} MB of weights)")


if __name__ == "__main__":
    main()
