"""設定スキーマ（`schema.py`）のテスト.

期待値は SPEC_02（原本と同じ学習条件）と SPEC_01「設定ファイル」を基準にする．
"""

from __future__ import annotations

from pathlib import Path
from typing import Any

import pytest
from pydantic import ValidationError

from tongue_seg_model.schema import ExperimentConfig, load_config

REPO_ROOT = Path(__file__).resolve().parents[1]
CONFIGS_DIR = REPO_ROOT / "configs"


def _minimal() -> dict[str, Any]:
    """必須項目（`data.bundle`）だけを持つ設定."""
    return {"data": {"bundle": {"name": "synthetic", "version": 1}}}


def _with(section: str, values: dict[str, Any]) -> dict[str, Any]:
    raw = _minimal()
    if section == "data":
        raw["data"].update(values)
    else:
        raw[section] = values
    return raw


def _write(tmp_path: Path, text: str, name: str = "config.yaml") -> Path:
    path = tmp_path / name
    path.write_text(text, encoding="utf-8")
    return path


# ---------------------------------------------------------------------------
# 既定値（SPEC_02 の表 = 原本と同じ学習条件）
# ---------------------------------------------------------------------------


class TestDefaultsMatchSpec02:
    @pytest.fixture
    def config(self) -> ExperimentConfig:
        return ExperimentConfig.model_validate(_minimal())

    def test_preprocessing_image_size_is_256x256(self, config: ExperimentConfig) -> None:
        assert tuple(config.data.image_size) == (256, 256)

    def test_split_defaults_to_random_with_two_thirds_for_training(
        self, config: ExperimentConfig
    ) -> None:
        assert config.data.split == "random"
        assert config.data.train_ratio == pytest.approx(2 / 3)

    def test_color_jitter_defaults_are_each_0_5(self, config: ExperimentConfig) -> None:
        cj = config.augment.color_jitter
        assert (cj.brightness, cj.contrast, cj.saturation, cj.hue) == (0.5, 0.5, 0.5, 0.5)

    def test_hflip_probability_defaults_to_0_5(self, config: ExperimentConfig) -> None:
        assert config.augment.hflip_prob == 0.5

    def test_model_uses_pretrained_weights_by_default(self, config: ExperimentConfig) -> None:
        assert config.model.pretrained is True
        assert config.model.pretrained_weights is None

    def test_loss_defaults_to_original_dice_ce(self, config: ExperimentConfig) -> None:
        assert config.loss.bce_weight == 0.5
        assert config.loss.bce_input == "sigmoid"

    def test_training_defaults_match_original(self, config: ExperimentConfig) -> None:
        train = config.train
        assert train.batch_size == 16
        assert train.learning_rate == pytest.approx(1e-4)
        assert train.max_epochs == 300
        assert train.early_stopping_patience == 30
        assert train.seed == 2021

    def test_export_opset_defaults_to_11(self, config: ExperimentConfig) -> None:
        assert config.export.opset == 11

    def test_run_out_dir_defaults_to_runs(self, config: ExperimentConfig) -> None:
        assert config.run.out_dir == Path("runs")

    def test_all_sections_are_filled_when_omitted(self, config: ExperimentConfig) -> None:
        dumped = config.model_dump(mode="json")
        assert set(dumped) == {"data", "augment", "model", "loss", "train", "export", "run"}


def test_explicit_values_override_defaults() -> None:
    raw = _minimal()
    raw["train"] = {"batch_size": 4, "max_epochs": 3, "seed": 7}
    raw["loss"] = {"bce_input": "logits", "bce_weight": 0.3}
    raw["data"]["split"] = "subject"
    config = ExperimentConfig.model_validate(raw)
    assert config.train.batch_size == 4
    assert config.train.max_epochs == 3
    assert config.train.seed == 7
    # 書いていない項目は既定のまま
    assert config.train.learning_rate == pytest.approx(1e-4)
    assert config.train.early_stopping_patience == 30
    assert config.loss.bce_input == "logits"
    assert config.loss.bce_weight == 0.3
    assert config.data.split == "subject"


def test_config_is_immutable() -> None:
    config = ExperimentConfig.model_validate(_minimal())
    with pytest.raises(ValidationError):
        config.train.batch_size = 1  # type: ignore[misc]


# ---------------------------------------------------------------------------
# 不正な設定は ValidationError で止まる
# ---------------------------------------------------------------------------


@pytest.mark.parametrize(
    "raw",
    [
        pytest.param({**_minimal(), "unknown": 1}, id="top-level"),
        pytest.param(_with("data", {"imagesize": [256, 256]}), id="data"),
        pytest.param(
            {"data": {"bundle": {"name": "a", "version": 1, "extra": 1}}}, id="data.bundle"
        ),
        pytest.param(_with("augment", {"hflip": 0.5}), id="augment"),
        pytest.param(_with("augment", {"color_jitter": {"gamma": 0.1}}), id="color_jitter"),
        pytest.param(_with("model", {"pretrain": False}), id="model"),
        pytest.param(_with("loss", {"dice_weight": 0.5}), id="loss"),
        pytest.param(_with("train", {"epochs": 3}), id="train"),
        pytest.param(_with("export", {"opset_version": 11}), id="export"),
        pytest.param(_with("run", {"output": "runs"}), id="run"),
    ],
)
def test_unknown_key_is_rejected(raw: dict[str, Any]) -> None:
    with pytest.raises(ValidationError):
        ExperimentConfig.model_validate(raw)


@pytest.mark.parametrize(
    "raw",
    [
        pytest.param({}, id="no-data"),
        pytest.param({"data": {}}, id="no-bundle"),
        pytest.param({"data": {"bundle": {"version": 1}}}, id="no-bundle-name"),
        pytest.param({"data": {"bundle": {"name": "synthetic"}}}, id="no-bundle-version"),
    ],
)
def test_missing_required_field_is_rejected(raw: dict[str, Any]) -> None:
    with pytest.raises(ValidationError):
        ExperimentConfig.model_validate(raw)


@pytest.mark.parametrize(
    "raw",
    [
        # data
        pytest.param({"data": {"bundle": {"name": "a", "version": 0}}}, id="bundle-version-0"),
        pytest.param({"data": {"bundle": {"name": "a", "version": "1"}}}, id="bundle-version-str"),
        pytest.param({"data": {"bundle": {"name": "", "version": 1}}}, id="bundle-name-empty"),
        pytest.param({"data": {"bundle": {"name": "../x", "version": 1}}}, id="bundle-name-path"),
        pytest.param(
            {"data": {"bundle": {"name": "a\n", "version": 1}}}, id="bundle-name-trailing-newline"
        ),
        pytest.param(_with("data", {"image_size": [0, 256]}), id="image-size-0"),
        pytest.param(_with("data", {"image_size": [256]}), id="image-size-1d"),
        pytest.param(_with("data", {"image_size": [256, 256, 3]}), id="image-size-3d"),
        pytest.param(_with("data", {"image_size": [256.5, 256]}), id="image-size-float"),
        pytest.param(_with("data", {"split": "patient"}), id="split-unknown"),
        pytest.param(_with("data", {"train_ratio": 0.0}), id="train-ratio-0"),
        pytest.param(_with("data", {"train_ratio": 1.0}), id="train-ratio-1"),
        pytest.param(_with("data", {"train_ratio": 1.5}), id="train-ratio-gt1"),
        pytest.param(_with("data", {"train_ratio": float("nan")}), id="train-ratio-nan"),
        # augment
        pytest.param(_with("augment", {"hflip_prob": -0.1}), id="hflip-negative"),
        pytest.param(_with("augment", {"hflip_prob": 1.1}), id="hflip-gt1"),
        pytest.param(
            _with("augment", {"color_jitter": {"brightness": -0.1}}), id="brightness-negative"
        ),
        pytest.param(_with("augment", {"color_jitter": {"hue": 0.6}}), id="hue-gt-0.5"),
        pytest.param(_with("augment", {"color_jitter": {"hue": -0.1}}), id="hue-negative"),
        # model
        pytest.param(_with("model", {"pretrained": "yes"}), id="pretrained-str"),
        pytest.param(
            _with("model", {"pretrained": False, "pretrained_weights": "w.pth"}),
            id="weights-without-pretrained",
        ),
        # loss
        pytest.param(_with("loss", {"bce_weight": 1.5}), id="bce-weight-gt1"),
        pytest.param(_with("loss", {"bce_weight": -0.1}), id="bce-weight-negative"),
        pytest.param(_with("loss", {"bce_input": "probs"}), id="bce-input-unknown"),
        # train
        pytest.param(_with("train", {"batch_size": 0}), id="batch-size-0"),
        pytest.param(_with("train", {"batch_size": 1.5}), id="batch-size-float"),
        pytest.param(_with("train", {"batch_size": "16"}), id="batch-size-str"),
        pytest.param(_with("train", {"learning_rate": 0.0}), id="lr-0"),
        pytest.param(_with("train", {"learning_rate": -1e-4}), id="lr-negative"),
        pytest.param(_with("train", {"max_epochs": 0}), id="max-epochs-0"),
        pytest.param(_with("train", {"early_stopping_patience": 0}), id="patience-0"),
        pytest.param(_with("train", {"seed": -1}), id="seed-negative"),
        pytest.param(_with("train", {"seed": 2**32}), id="seed-too-large"),
        pytest.param(_with("train", {"num_workers": -1}), id="num-workers-negative"),
        pytest.param(_with("train", {"device": "gpu"}), id="device-unknown"),
        pytest.param(_with("train", {"device": "cuda:"}), id="device-cuda-colon"),
        pytest.param(_with("train", {"device": "cpu\n"}), id="device-trailing-newline"),
        # export
        pytest.param(_with("export", {"opset": 6}), id="opset-too-old"),
        pytest.param(_with("export", {"opset": "11"}), id="opset-str"),
    ],
)
def test_out_of_range_or_wrong_type_is_rejected(raw: dict[str, Any]) -> None:
    with pytest.raises(ValidationError):
        ExperimentConfig.model_validate(raw)


@pytest.mark.parametrize("device", ["auto", "cpu", "cuda", "cuda:0", "cuda:3"])
def test_valid_device_is_accepted(device: str) -> None:
    config = ExperimentConfig.model_validate(_with("train", {"device": device}))
    assert config.train.device == device


def test_pretrained_weights_path_is_accepted_when_pretrained(tmp_path: Path) -> None:
    weights = tmp_path / "resnet18.pth"
    config = ExperimentConfig.model_validate(
        _with("model", {"pretrained": True, "pretrained_weights": str(weights)})
    )
    assert config.model.pretrained_weights == weights


def test_image_size_accepts_yaml_list() -> None:
    config = ExperimentConfig.model_validate(_with("data", {"image_size": [128, 64]}))
    assert tuple(config.data.image_size) == (128, 64)


# ---------------------------------------------------------------------------
# load_config
# ---------------------------------------------------------------------------


def test_load_config_fills_defaults(tmp_path: Path) -> None:
    path = _write(tmp_path, "data:\n  bundle:\n    name: synthetic\n    version: 2\n")
    config = load_config(path)
    assert config.data.bundle.name == "synthetic"
    assert config.data.bundle.version == 2
    assert config.train.batch_size == 16
    assert config.export.opset == 11


def test_load_config_rejects_unknown_key_in_yaml(tmp_path: Path) -> None:
    path = _write(
        tmp_path,
        "data:\n  bundle:\n    name: synthetic\n    version: 1\ntrain:\n  batchsize: 4\n",
    )
    with pytest.raises(ValidationError):
        load_config(path)


def test_load_config_rejects_malformed_yaml(tmp_path: Path) -> None:
    path = _write(tmp_path, "data: [unclosed\n  bundle: {name: a\n")
    with pytest.raises((ValueError, ValidationError)):
        load_config(path)


@pytest.mark.parametrize(
    "text",
    [
        pytest.param("- a\n- b\n", id="list"),
        pytest.param("just a string\n", id="scalar"),
    ],
)
def test_load_config_rejects_non_mapping_top_level(tmp_path: Path, text: str) -> None:
    path = _write(tmp_path, text)
    with pytest.raises((ValueError, ValidationError)):
        load_config(path)


def test_load_config_empty_file_fails_for_missing_bundle(tmp_path: Path) -> None:
    path = _write(tmp_path, "")
    with pytest.raises(ValidationError):
        load_config(path)


def test_load_config_missing_file_raises(tmp_path: Path) -> None:
    with pytest.raises(ValueError):
        load_config(tmp_path / "does_not_exist.yaml")


# ---------------------------------------------------------------------------
# リポジトリの configs/*.yaml
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("name", ["synthetic.yaml", "resunet.yaml"])
def test_repository_configs_are_valid(name: str) -> None:
    load_config(CONFIGS_DIR / name)


def test_resunet_config_keeps_original_training_conditions() -> None:
    """`configs/resunet.yaml` は原本と同じ学習条件（SPEC_01「設定ファイル」）."""
    config = load_config(CONFIGS_DIR / "resunet.yaml")
    defaults = ExperimentConfig.model_validate(
        {"data": config.data.model_dump(mode="json", include={"bundle"})}
    )
    assert config.data.image_size == defaults.data.image_size
    assert config.data.split == defaults.data.split
    assert config.data.train_ratio == defaults.data.train_ratio
    assert config.augment == defaults.augment
    assert config.model.pretrained is True
    assert config.loss == defaults.loss
    assert config.export == defaults.export
    t = config.train
    assert (t.batch_size, t.learning_rate, t.max_epochs, t.early_stopping_patience, t.seed) == (
        16,
        pytest.approx(1e-4),
        300,
        30,
        2021,
    )


def test_synthetic_config_runs_locally_without_download() -> None:
    """`configs/synthetic.yaml` は手元で流す設定（エポック数を小さく，事前学習の重みを使わない）."""
    config = load_config(CONFIGS_DIR / "synthetic.yaml")
    assert config.model.pretrained is False
    assert config.train.max_epochs < 300
    assert config.train.device == "cpu"
