"""ONNX の書き出しと読み込み・推論（`export/onnx_export.py`）のテスト.

期待値は SPEC_02「ONNX の書き出し」（原本と同じ条件: 入力 `(1, 3, 256, 256)` float32 → 出力
`(1, 2, 256, 256)` float32・推論モード・opset 11．onnxruntime（CPU）で読めること・PyTorch の
出力との差が小さいこと）と `.claude/rules/testing.md` の必須対象 9 を基準にする．

実際に ResUNet を書き出すテストは `slow`（1 回だけ書き出して module スコープで共有する）．
`read_onnx_info`・`run_onnxruntime` の細かい場合分けは，onnx.helper で作る小さなグラフで確かめる．
"""

from __future__ import annotations

from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path

import numpy as np
import onnx
import pytest
import torch
from onnx import TensorProto, helper

from tongue_seg_model.export.check import (
    CHECK_INPUT_SEED,
    MAX_ABS_DIFF_TOLERANCE,
    OnnxModelInfo,
    TensorSpec,
    export_input_shape,
    export_output_shape,
    find_export_problems,
    make_check_input,
    max_abs_diff,
)
from tongue_seg_model.export.onnx_export import (
    ONNX_FILENAME,
    export_to_onnx,
    read_onnx_info,
    run_onnxruntime,
    run_pytorch,
)
from tongue_seg_model.models.resunet import ResUNet


def test_onnx_filename_is_same_as_original() -> None:
    assert ONNX_FILENAME == "ResUNet.onnx"


# ---------------------------------------------------------------------------
# 小さなグラフでの読み込み・推論
# ---------------------------------------------------------------------------


def _save(model: onnx.ModelProto, path: Path) -> Path:
    onnx.save(model, str(path))
    return path


def _identity_model(
    *,
    shape: list[int | str] | None = None,
    opset_imports: list[onnx.OperatorSetIdProto] | None = None,
    with_initializer_input: bool = False,
    second_input: bool = False,
) -> onnx.ModelProto:
    shape = [1, 3, 4, 4] if shape is None else shape
    x = helper.make_tensor_value_info("x", TensorProto.FLOAT, shape)
    y = helper.make_tensor_value_info("y", TensorProto.FLOAT, shape)
    nodes = [helper.make_node("Identity", ["x"], ["y"])]
    inputs = [x]
    initializers = []
    if with_initializer_input:
        # 古い書き出し方では重みもグラフの入力に並ぶ（重みは入力として数えない）
        w = helper.make_tensor("w", TensorProto.FLOAT, [1], [0.0])
        initializers.append(w)
        inputs.append(helper.make_tensor_value_info("w", TensorProto.FLOAT, [1]))
    if second_input:
        inputs.append(helper.make_tensor_value_info("z", TensorProto.FLOAT, shape))
    graph = helper.make_graph(nodes, "g", inputs, [y], initializer=initializers)
    opsets = [helper.make_opsetid("", 11)] if opset_imports is None else opset_imports
    model = helper.make_model(graph, opset_imports=opsets)
    model.ir_version = 7
    return model


class TestReadOnnxInfo:
    def test_reads_opset_inputs_outputs(self, tmp_path: Path) -> None:
        path = _save(_identity_model(), tmp_path / "m.onnx")
        assert read_onnx_info(path) == OnnxModelInfo(
            opset=11,
            inputs=(TensorSpec("x", (1, 3, 4, 4), "float32"),),
            outputs=(TensorSpec("y", (1, 3, 4, 4), "float32"),),
        )

    def test_excludes_initializers_from_inputs(self, tmp_path: Path) -> None:
        path = _save(_identity_model(with_initializer_input=True), tmp_path / "m.onnx")
        info = read_onnx_info(path)
        assert [spec.name for spec in info.inputs] == ["x"]

    def test_dynamic_dims_become_names(self, tmp_path: Path) -> None:
        path = _save(_identity_model(shape=["batch", 3, 4, 4]), tmp_path / "m.onnx")
        info = read_onnx_info(path)
        assert info.inputs[0].shape == ("batch", 3, 4, 4)

    def test_reads_default_domain_opset_among_others(self, tmp_path: Path) -> None:
        opsets = [helper.make_opsetid("com.example", 1), helper.make_opsetid("", 13)]
        path = _save(_identity_model(opset_imports=opsets), tmp_path / "m.onnx")
        assert read_onnx_info(path).opset == 13

    def test_reads_ai_onnx_domain_name(self, tmp_path: Path) -> None:
        path = _save(
            _identity_model(opset_imports=[helper.make_opsetid("ai.onnx", 12)]), tmp_path / "m.onnx"
        )
        assert read_onnx_info(path).opset == 12

    def test_missing_file_is_value_error(self, tmp_path: Path) -> None:
        with pytest.raises(ValueError):
            read_onnx_info(tmp_path / "missing.onnx")

    def test_garbage_file_is_value_error(self, tmp_path: Path) -> None:
        path = tmp_path / "bad.onnx"
        path.write_bytes(b"this is not an onnx model\x00\xff" * 10)
        with pytest.raises(ValueError):
            read_onnx_info(path)

    def test_model_failing_checker_is_value_error(self, tmp_path: Path) -> None:
        model = _identity_model()
        model.graph.node[0].input[0] = "undefined_tensor"
        path = _save(model, tmp_path / "m.onnx")
        with pytest.raises(ValueError):
            read_onnx_info(path)


class TestRunOnnxruntime:
    def test_runs_identity(self, tmp_path: Path) -> None:
        path = _save(_identity_model(), tmp_path / "m.onnx")
        x = make_check_input((1, 3, 4, 4), 0)
        y = run_onnxruntime(path, x)
        assert isinstance(y, np.ndarray)
        np.testing.assert_array_equal(y, x)

    def test_two_inputs_is_value_error(self, tmp_path: Path) -> None:
        path = _save(_identity_model(second_input=True), tmp_path / "m.onnx")
        with pytest.raises(ValueError, match="入力"):
            run_onnxruntime(path, make_check_input((1, 3, 4, 4), 0))

    def test_wrong_input_shape_is_value_error(self, tmp_path: Path) -> None:
        path = _save(_identity_model(), tmp_path / "m.onnx")
        with pytest.raises(ValueError):
            run_onnxruntime(path, make_check_input((1, 3, 8, 8), 0))

    def test_garbage_file_is_value_error(self, tmp_path: Path) -> None:
        path = tmp_path / "bad.onnx"
        path.write_bytes(b"not onnx" * 10)
        with pytest.raises(ValueError):
            run_onnxruntime(path, make_check_input((1, 3, 4, 4), 0))

    def test_missing_file_is_value_error(self, tmp_path: Path) -> None:
        with pytest.raises(ValueError):
            run_onnxruntime(tmp_path / "missing.onnx", make_check_input((1, 3, 4, 4), 0))


# ---------------------------------------------------------------------------
# ResUNet の書き出し（slow）
# ---------------------------------------------------------------------------

SIZE = (256, 256)


@dataclass(frozen=True)
class Exported:
    model: ResUNet
    path: Path
    warnings: list[str]


@pytest.fixture(scope="module")
def exported(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Exported]:
    """乱数の重みの ResUNet を 256×256・opset 11 で 1 回書き出す（このモジュールで共有する）."""
    torch.manual_seed(0)
    model = ResUNet(pretrained=False)
    path = tmp_path_factory.mktemp("onnx") / ONNX_FILENAME
    warnings = export_to_onnx(model, path, input_shape=export_input_shape(SIZE), opset=11)
    try:
        yield Exported(model=model, path=path, warnings=warnings)
    finally:
        path.unlink(missing_ok=True)  # 約 70MB のファイルを残さない


@pytest.mark.slow
class TestExportResUNet:
    def test_file_is_written(self, exported: Exported) -> None:
        assert exported.path.is_file()
        assert exported.path.stat().st_size > 0

    def test_model_is_left_in_eval_mode(self, exported: Exported) -> None:
        assert not exported.model.training

    def test_warnings_are_returned_as_strings(self, exported: Exported) -> None:
        assert all(isinstance(message, str) for message in exported.warnings)

    def test_opset_is_11(self, exported: Exported) -> None:
        assert read_onnx_info(exported.path).opset == 11

    def test_input_and_output_match_spec02(self, exported: Exported) -> None:
        info = read_onnx_info(exported.path)
        assert len(info.inputs) == 1
        assert len(info.outputs) == 1
        assert info.inputs[0].shape == (1, 3, 256, 256)
        assert info.inputs[0].elem_type == "float32"
        assert info.outputs[0].shape == (1, 2, 256, 256)
        assert info.outputs[0].elem_type == "float32"

    def test_onnxruntime_output_matches_pytorch(self, exported: Exported) -> None:
        x = make_check_input(export_input_shape(SIZE), CHECK_INPUT_SEED)
        expected = run_pytorch(exported.model, x)
        actual = run_onnxruntime(exported.path, x)
        assert expected.shape == (1, 2, 256, 256)
        assert actual.shape == (1, 2, 256, 256)
        assert actual.dtype == np.float32
        assert max_abs_diff(expected, actual) <= MAX_ABS_DIFF_TOLERANCE

    def test_output_is_raw_logits_not_activated(self, exported: Exported) -> None:
        # 出力は活性化関数を掛ける前の値（0〜1 に収まるとは限らない．シグモイドの値でない）
        x = make_check_input(export_input_shape(SIZE), CHECK_INPUT_SEED)
        actual = run_onnxruntime(exported.path, x)
        with torch.no_grad():
            expected = exported.model(torch.from_numpy(x)).numpy()
        np.testing.assert_allclose(actual, expected, atol=MAX_ABS_DIFF_TOLERANCE, rtol=0)

    def test_no_problems_found(self, exported: Exported) -> None:
        x = make_check_input(export_input_shape(SIZE), CHECK_INPUT_SEED)
        expected = run_pytorch(exported.model, x)
        actual = run_onnxruntime(exported.path, x)
        problems = find_export_problems(
            read_onnx_info(exported.path),
            opset=11,
            input_shape=export_input_shape(SIZE),
            output_shape=export_output_shape(SIZE, 2),
            runtime_output_shape=actual.shape,
            runtime_output_dtype=actual.dtype.name,
            diff=max_abs_diff(expected, actual),
        )
        assert problems == []


def test_run_pytorch_uses_eval_mode() -> None:
    # 推論モード（BatchNorm が移動平均を使う）．同じ入力の 2 回の結果が一致し，学習モードと異なる
    torch.manual_seed(0)
    model = ResUNet(pretrained=False)
    model.train()
    x = make_check_input((1, 3, 64, 64), 0)
    first = run_pytorch(model, x)
    assert not model.training
    assert first.shape == (1, 2, 64, 64)
    assert first.dtype == np.float32
    np.testing.assert_array_equal(first, run_pytorch(model, x))
    model.eval()
    with torch.no_grad():
        np.testing.assert_array_equal(first, model(torch.from_numpy(x)).numpy())


@pytest.mark.slow
def test_unsupported_opset_is_value_error(tmp_path: Path) -> None:
    # ResUNet の bilinear（align_corners=True）の拡大は opset 11 より前では書き出せない
    path = tmp_path / ONNX_FILENAME
    with pytest.raises(ValueError, match="opset 10"):
        export_to_onnx(ResUNet(pretrained=False), path, input_shape=(1, 3, 64, 64), opset=10)
    assert not path.exists()
