# Copyright (C) 2026 Embedl AB
# mypy: disable-error-code="no-untyped-call"
"""
ONNX export helpers
===================

Export a model to ONNX and simplify it with ``onnxsim``. Several tutorials
build their TensorRT engines from this, so it lives here rather than in any one
of them.
"""

# %%
from dataclasses import dataclass
from pathlib import Path

import onnx
import onnxsim
import torch
from torch import nn


@dataclass(frozen=True)
class ExportResult:
    """Files produced by ONNX export."""

    raw_path: Path
    model_path: Path
    simplified: bool
    #: Weights sidecar beside `raw_path`, which the `torch.export` exporter
    #: writes whenever it exports with external data -- its default. Without it
    #: `raw_path` is a graph with no initializer values in it.
    data_path: Path | None = None


def export_and_simplify(
    model: nn.Module, onnx_path: Path, crop_size: int = 224
) -> ExportResult:
    """Export to ONNX and simplify with onnxsim.

    The example input follows the model's own dtype, and the export uses the
    `torch.export`-based exporter, which a float16 quantized graph requires.
    Opset 19 preserves GridSample's interpolation names for TensorRT before
    11.2 while supporting float16 and FP8 Q/DQ. GELU is decomposed by the
    exporter into operators available at this opset.
    """
    model = model.cpu().eval()
    dtypes = [p.dtype for p in model.parameters() if p.is_floating_point()]
    dtype = torch.float16 if torch.float16 in dtypes else dtypes[0]
    x = torch.randn(1, 3, crop_size, crop_size, dtype=dtype)
    torch.onnx.export(
        model,
        (x,),
        str(onnx_path),
        opset_version=19,
        input_names=["input"],
        output_names=["output"],
        dynamo=True,
    )
    onnx_model = onnx.load(str(onnx_path))
    simplified, ok = onnxsim.simplify(onnx_model)
    simp_path = onnx_path.with_name(onnx_path.stem + "_sim.onnx")
    if ok:
        onnx.save(simplified, str(simp_path))
        print(f"  Simplified ONNX: {simp_path}")
    else:
        print("  onnxsim failed; using raw export.")
        simp_path = onnx_path
    data_path = onnx_path.with_name(onnx_path.name + ".data")
    return ExportResult(
        raw_path=onnx_path,
        model_path=simp_path,
        simplified=ok,
        data_path=data_path if data_path.exists() else None,
    )
