"""前任者の手法の比較の設定のテスト（SPEC_02「前任者の手法との比較」「データ拡張」）.

- 不正な設定は `ValidationError`
- **色を変える処理は既定で無効**．`configs/predecessor/` の外の設定では有効にしない
- `configs/predecessor/` の実データ用の設定の値が SPEC_02 の表と一致する
"""

from __future__ import annotations

from pathlib import Path

import pytest
import yaml
from pydantic import ValidationError

from tias_judge_model.schema import ExperimentConfig, TrainConfig, load_config

CONFIGS_DIR = Path(__file__).resolve().parents[1] / "configs"
PREDECESSOR_DIR = CONFIGS_DIR / "predecessor"
SYNTHETIC_DIR = PREDECESSOR_DIR / "synthetic"
SEG_DIR = CONFIGS_DIR / "seg"
CONDITIONS = {
    "with_mild": {"strong", "mild", "normal"},
    "without_mild": {"strong", "normal"},
}
RESNET_METHODS = {
    "cv_pred_resnet34": "none",
    "cv_pred_resnet34_color_shift_real_plus_pseudo": "real_plus_pseudo",
    "cv_pred_resnet34_color_shift_pseudo_only": "pseudo_only",
}
SVM_FEATURES = {
    "cv_color_svm_lateral": "deeptias_lateral",
    "cv_color_svm_coat_removed": "tongue_body",
    "cv_color_svm_coat_removed_slide": "tongue_body",
}
THRESHOLDS = {
    "cv_color_svm_coat_removed": (
        {"h": (0, 180), "s": (0, 92), "v": (0, 255)},
        {"h": (0, 89), "s": (0, 255), "v": (0, 255)},
    ),
    "cv_color_svm_coat_removed_slide": (
        {"h": (0, 180), "s": (0, 80), "v": (0, 255)},
        {"h": (0, 20), "s": (0, 255), "v": (0, 255)},
    ),
}


def _experiment_configs_outside_predecessor() -> list[Path]:
    return sorted(
        p
        for p in CONFIGS_DIR.rglob("*.yaml")
        if p.name != "remote.yaml" and SEG_DIR not in p.parents and PREDECESSOR_DIR not in p.parents
    )


def _load(stem: str, condition: str) -> ExperimentConfig:
    return load_config(PREDECESSOR_DIR / f"{stem}_{condition}.yaml", environ={})


# --- 既定で色を変えない ---


def test_defaults_do_not_change_colors() -> None:
    config = ExperimentConfig.model_validate({"data": {"root": "d"}})
    assert config.train.augmentation.color_jitter is None
    assert config.train.color_shift_pseudo.mode == "none"


def test_default_geometric_augmentation_matches_spec() -> None:
    augmentation = TrainConfig().augmentation
    assert augmentation.horizontal_flip_prob == 0.5
    assert augmentation.rotation_degrees == 10.0
    assert augmentation.scale_range == (0.9, 1.1)
    assert augmentation.translate_ratio == 0.05


def test_outside_list_is_not_empty() -> None:
    assert len(_experiment_configs_outside_predecessor()) >= 100


@pytest.mark.parametrize(
    "path",
    _experiment_configs_outside_predecessor(),
    ids=lambda p: p.relative_to(CONFIGS_DIR).as_posix(),
)
def test_other_configs_do_not_change_colors(path: Path) -> None:
    train = load_config(path, environ={}).train
    assert train.augmentation.color_jitter is None
    assert train.color_shift_pseudo.mode == "none"


def test_color_jitter_needs_all_items_explicitly() -> None:
    # 「色を変える」を暗黙の既定値で有効にしない
    with pytest.raises(ValidationError):
        TrainConfig.model_validate({"augmentation": {"color_jitter": {"brightness": 0.05}}})


# --- 不正な設定 ---


@pytest.mark.parametrize(
    "augmentation",
    [
        {"horizontal_flip_prob": 1.5},
        {"horizontal_flip_prob": -0.1},
        {"rotation_degrees": -1},
        {"rotation_degrees": 181},
        {"scale_range": [1.1, 0.9]},
        {"scale_range": [0.0, 1.0]},
        {"scale_range": [-0.5, 1.0]},
        {"scale_range": [1.0]},
        {"scale_range": [0.9, 1.0, 1.1]},
        {"translate_ratio": -0.1},
        {"translate_ratio": 1.5},
        {"flip": 0.5},  # 未知のキー
        {"color_jitter": {"brightness": 0.1, "contrast": 0.1, "saturation": 0.1}},  # hue が無い
        {"color_jitter": {"brightness": -0.1, "contrast": 0.1, "saturation": 0.1, "hue": 0.1}},
        {"color_jitter": {"brightness": 0.1, "contrast": -0.1, "saturation": 0.1, "hue": 0.1}},
        {"color_jitter": {"brightness": 0.1, "contrast": 0.1, "saturation": -0.1, "hue": 0.1}},
        {"color_jitter": {"brightness": 0.1, "contrast": 0.1, "saturation": 0.1, "hue": 0.6}},
        {"color_jitter": {"brightness": 0.1, "contrast": 0.1, "saturation": 0.1, "hue": -0.1}},
        {
            "color_jitter": {
                "brightness": 0.1,
                "contrast": 0.1,
                "saturation": 0.1,
                "hue": 0.1,
                "gamma": 0.1,
            }
        },
    ],
    ids=str,
)
def test_invalid_augmentation_is_rejected(augmentation: dict) -> None:
    with pytest.raises(ValidationError):
        TrainConfig.model_validate({"augmentation": augmentation})


@pytest.mark.parametrize(
    "pseudo",
    [
        {"mode": "both"},
        {"mode": ""},
        {"mode": None},
        {"uniform_half_range": -0.1},
        {"uniform_half_range": "wide"},
        {"modes": "pseudo_only"},  # 未知のキー
    ],
    ids=str,
)
def test_invalid_color_shift_pseudo_is_rejected(pseudo: dict) -> None:
    with pytest.raises(ValidationError):
        TrainConfig.model_validate({"color_shift_pseudo": pseudo})


@pytest.mark.parametrize("mode", ["real_plus_pseudo", "pseudo_only"])
@pytest.mark.parametrize(
    "balance",
    [
        {"class_weighting": "inverse"},
        {"class_weighting": "sqrt_inverse"},
        {"sampler": "balanced"},
    ],
    ids=str,
)
def test_pseudo_cannot_be_combined_with_imbalance_countermeasures(mode: str, balance: dict) -> None:
    with pytest.raises(ValidationError):
        TrainConfig.model_validate({"color_shift_pseudo": {"mode": mode}, **balance})


def test_pseudo_mode_none_can_be_combined_with_imbalance_countermeasures() -> None:
    config = TrainConfig.model_validate(
        {"color_shift_pseudo": {"mode": "none"}, "class_weighting": "inverse"}
    )
    assert config.class_weighting == "inverse"


GOOD_RANGE = {"h": [0, 180], "s": [0, 92], "v": [0, 255]}
GOOD_COAT = {"white": GOOD_RANGE, "yellow": GOOD_RANGE}


@pytest.mark.parametrize(
    "color",
    [
        {"classifier": "svm"},
        {"classifier": "svm_linear"},
        {"features": "unknown"},
        {"svm": {"c_values": []}},
        {"svm": {"c_values": [0]}},
        {"svm": {"c_values": [-1.0]}},
        {"svm": {"c_values": [1.0, 1.0]}},
        {"svm": {"c_values": ["large"]}},
        {"svm": {"gammas": []}},
        {"svm": {"gammas": [0]}},
        {"svm": {"gammas": [-0.1]}},
        {"svm": {"gammas": ["auto"]}},
        {"svm": {"gammas": [0.1, 0.1]}},
        {"svm": {"gammas": ["scale", "scale"]}},
        {"svm": {"class_weight": "weighted"}},
        {"svm": {"kernel": "linear"}},  # 未知のキー
        {"features": "tongue_body", "max_side": None},  # coat_removal が無い
        {"features": "color_stats", "coat_removal": GOOD_COAT},  # tongue_body 以外に指定
        {"features": "deeptias_lateral", "coat_removal": GOOD_COAT},
        {"coat_removal": GOOD_COAT},  # 既定の color_stats に指定
        {
            "features": "tongue_body",
            "max_side": None,
            "coat_removal": {"white": GOOD_RANGE},  # yellow が無い
        },
        {
            "features": "tongue_body",
            "max_side": None,
            "coat_removal": {"yellow": GOOD_RANGE},  # white が無い
        },
        {
            "features": "tongue_body",
            "max_side": None,
            "coat_removal": {**GOOD_COAT, "green": GOOD_RANGE},  # 未知のキー
        },
    ],
    ids=str,
)
def test_invalid_color_settings_are_rejected(color: dict) -> None:
    with pytest.raises(ValidationError):
        ExperimentConfig.model_validate({"data": {"root": "d"}, "color": color})


@pytest.mark.parametrize(
    "hsv",
    [
        {"h": [0, 180], "s": [0, 92]},  # v が無い
        {"h": [0, 180], "s": [0, 92], "v": [0, 255], "x": [0, 1]},  # 未知のキー
        {"h": [10, 5], "s": [0, 92], "v": [0, 255]},  # 下限 > 上限
        {"h": [0, 180], "s": [93, 92], "v": [0, 255]},
        {"h": [0, 181], "s": [0, 92], "v": [0, 255]},  # OpenCV の値域の外
        {"h": [-1, 180], "s": [0, 92], "v": [0, 255]},
        {"h": [0, 180], "s": [0, 256], "v": [0, 255]},
        {"h": [0, 180], "s": [-1, 92], "v": [0, 255]},
        {"h": [0, 180], "s": [0, 92], "v": [0, 256]},
        {"h": [0, 180], "s": [0, 92], "v": [-1, 255]},
        {"h": [0], "s": [0, 92], "v": [0, 255]},
        {"h": [0.5, 10], "s": [0, 92], "v": [0, 255]},
    ],
    ids=str,
)
def test_invalid_hsv_range_is_rejected(hsv: dict) -> None:
    # max_side を書く．省くと HSV が正しくても止まり，HSV の検証を確かめたことにならない
    color = {
        "features": "tongue_body",
        "max_side": None,
        "coat_removal": {"white": hsv, "yellow": GOOD_RANGE},
    }
    with pytest.raises(ValidationError):
        ExperimentConfig.model_validate({"data": {"root": "d"}, "color": color})


@pytest.mark.parametrize("pair", [[False, True], [0, True], [False, 90]], ids=str)
@pytest.mark.parametrize("key", ["h", "s", "v"])
def test_hsv_range_rejects_booleans(key: str, pair: list) -> None:
    # pydantic は真偽値を 0・1 の整数として通すので，別に止めている
    color = {
        "features": "tongue_body",
        "max_side": None,
        "coat_removal": {"white": {**GOOD_RANGE, key: pair}, "yellow": GOOD_RANGE},
    }
    with pytest.raises(ValidationError) as excinfo:
        ExperimentConfig.model_validate({"data": {"root": "d"}, "color": color})
    assert all(key in error["loc"] for error in excinfo.value.errors())


# --- 有限でない数 ---

NON_FINITE = [float("nan"), float("inf"), float("-inf")]
GOOD_JITTER = {"brightness": 0.1, "contrast": 0.1, "saturation": 0.1, "hue": 0.1}


def _assert_rejected_at(build, key: str) -> None:
    # 別の理由で止まったのでないことを，エラーの位置で確かめる
    with pytest.raises(ValidationError) as excinfo:
        build()
    errors = excinfo.value.errors()
    assert errors
    assert all(key in error["loc"] for error in errors), errors


def _validate_color(color: dict) -> ExperimentConfig:
    return ExperimentConfig.model_validate({"data": {"root": "d"}, "color": color})


@pytest.mark.parametrize("bad", NON_FINITE, ids=str)
@pytest.mark.parametrize(
    ("make_color", "key"),
    [
        pytest.param(lambda v: {"logistic": {"c_values": [v]}}, "c_values", id="logistic_c"),
        pytest.param(lambda v: {"svm": {"c_values": [v]}}, "c_values", id="svm_c"),
        pytest.param(lambda v: {"svm": {"c_values": [1.0, v]}}, "c_values", id="svm_c_second"),
        pytest.param(lambda v: {"svm": {"gammas": [v]}}, "gammas", id="svm_gamma"),
        pytest.param(lambda v: {"svm": {"gammas": ["scale", v]}}, "gammas", id="svm_gamma_second"),
    ],
)
def test_non_finite_color_candidates_are_rejected(make_color, key: str, bad: float) -> None:
    _assert_rejected_at(lambda: _validate_color(make_color(bad)), key)


@pytest.mark.parametrize("bad", NON_FINITE, ids=str)
def test_non_finite_uniform_half_range_is_rejected(bad: float) -> None:
    _assert_rejected_at(
        lambda: TrainConfig.model_validate({"color_shift_pseudo": {"uniform_half_range": bad}}),
        "uniform_half_range",
    )


@pytest.mark.parametrize("bad", NON_FINITE, ids=str)
@pytest.mark.parametrize(
    "make_range",
    [
        pytest.param(lambda v: [v, 1.0], id="low"),
        pytest.param(lambda v: [0.9, v], id="high"),
    ],
)
def test_non_finite_scale_range_is_rejected(make_range, bad: float) -> None:
    _assert_rejected_at(
        lambda: TrainConfig.model_validate({"augmentation": {"scale_range": make_range(bad)}}),
        "scale_range",
    )


@pytest.mark.parametrize("bad", NON_FINITE, ids=str)
@pytest.mark.parametrize("key", GOOD_JITTER)
def test_non_finite_color_jitter_is_rejected(key: str, bad: float) -> None:
    jitter = {**GOOD_JITTER, key: bad}
    _assert_rejected_at(
        lambda: TrainConfig.model_validate({"augmentation": {"color_jitter": jitter}}), key
    )


@pytest.mark.parametrize("text", [".nan", ".inf", "-.inf"])
def test_non_finite_values_in_yaml_are_rejected(tmp_path: Path, text: str) -> None:
    # 設定ファイルの書き方（YAML の .nan・.inf）でも止まる
    path = tmp_path / "bad.yaml"
    path.write_text(
        f"data: {{root: d}}\ncolor: {{svm: {{c_values: [{text}]}}}}\n", encoding="utf-8"
    )
    with pytest.raises(ValidationError):
        load_config(path, environ={})


def test_gamma_scale_alone_is_accepted() -> None:
    color = _validate_color({"svm": {"gammas": ["scale"]}}).color
    assert color is not None
    assert color.svm.gammas == ("scale",)


@pytest.mark.parametrize(
    "jitter",
    [
        GOOD_JITTER,
        {"brightness": 0.0, "contrast": 0.0, "saturation": 0.0, "hue": 0.0},
        {"brightness": 2.0, "contrast": 2.0, "saturation": 2.0, "hue": 0.5},  # hue の上限
    ],
    ids=str,
)
def test_valid_color_jitter_is_accepted(jitter: dict) -> None:
    config = TrainConfig.model_validate({"augmentation": {"color_jitter": jitter}})
    assert config.augmentation.color_jitter is not None
    assert config.augmentation.color_jitter.model_dump() == jitter


# --- max_side（tongue_body では省けない） ---


def test_tongue_body_without_max_side_is_rejected() -> None:
    # 省くと既定の 512 で黙って縮小され，仕様（元の解像度）と違う特徴量になる
    with pytest.raises(ValidationError, match="max_side"):
        _validate_color({"features": "tongue_body", "coat_removal": GOOD_COAT})


@pytest.mark.parametrize("max_side", [None, 64])
def test_tongue_body_with_explicit_max_side_is_accepted(max_side: int | None) -> None:
    color = _validate_color(
        {"features": "tongue_body", "coat_removal": GOOD_COAT, "max_side": max_side}
    ).color
    assert color is not None
    assert color.max_side == max_side


def test_tongue_body_without_max_side_in_yaml_is_rejected(tmp_path: Path) -> None:
    body = yaml.safe_dump(
        {"data": {"root": "d"}, "color": {"features": "tongue_body", "coat_removal": GOOD_COAT}}
    )
    path = tmp_path / "config.yaml"
    path.write_text(body, encoding="utf-8")
    with pytest.raises(ValidationError, match="max_side"):
        load_config(path, environ={})

    doc = yaml.safe_load(body)
    doc["color"]["max_side"] = None
    path.write_text(yaml.safe_dump(doc), encoding="utf-8")
    color = load_config(path, environ={}).color
    assert color is not None
    assert color.max_side is None


@pytest.mark.parametrize("features", ["color_stats", "deeptias_lateral"])
def test_other_features_can_omit_max_side(features: str) -> None:
    color = _validate_color({"features": features}).color
    assert color is not None
    assert color.max_side == 512


def test_svm_defaults_match_spec() -> None:
    config = ExperimentConfig.model_validate(
        {"data": {"root": "d"}, "color": {"classifier": "svm_rbf"}}
    )
    assert config.color is not None
    assert config.color.features == "color_stats"
    assert config.color.svm.c_values == (0.1, 1.0, 10.0, 100.0)
    assert config.color.svm.gammas == ("scale", 0.01, 0.1, 1.0)
    assert config.color.svm.class_weight == "balanced"


def test_svm_class_weight_can_be_null() -> None:
    config = ExperimentConfig.model_validate(
        {"data": {"root": "d"}, "color": {"classifier": "svm_rbf", "svm": {"class_weight": None}}}
    )
    assert config.color is not None
    assert config.color.svm.class_weight is None


# --- configs/predecessor/ の設定が SPEC_02 の表と一致する ---


def test_predecessor_config_files_are_exactly_the_spec_table() -> None:
    expected = {
        f"{stem}_{condition}.yaml"
        for stem in (*RESNET_METHODS, *SVM_FEATURES)
        for condition in CONDITIONS
    }
    assert {p.name for p in PREDECESSOR_DIR.glob("*.yaml")} == expected
    assert len(expected) == 12


@pytest.mark.parametrize("condition", CONDITIONS)
@pytest.mark.parametrize("stem", RESNET_METHODS)
def test_resnet_configs_match_spec(stem: str, condition: str) -> None:
    config = _load(stem, condition)
    assert set(config.data.severities) == CONDITIONS[condition]
    assert config.model.name == "resnet34"
    assert config.model.pretrained is True
    train = config.train
    assert train.image_size == 224
    assert train.lr == pytest.approx(1.285e-4)
    assert train.weight_decay == pytest.approx(1e-4)
    assert train.batch_size == 32
    assert train.max_epochs == 200
    assert train.patience == 50
    assert train.warmup_epochs == 0
    assert train.class_weighting == "none"
    assert train.sampler == "random"

    augmentation = train.augmentation
    assert augmentation.horizontal_flip_prob == 0.5
    assert augmentation.rotation_degrees == 5.0
    assert augmentation.scale_range is None
    assert augmentation.translate_ratio == 0.0
    jitter = augmentation.color_jitter
    assert jitter is not None  # この比較の設定では明示的に有効にする
    assert (jitter.brightness, jitter.contrast, jitter.saturation, jitter.hue) == (
        0.05,
        0.05,
        0.05,
        0.05,
    )

    assert train.color_shift_pseudo.mode == RESNET_METHODS[stem]
    assert train.color_shift_pseudo.uniform_half_range == 0.5


@pytest.mark.parametrize("condition", CONDITIONS)
@pytest.mark.parametrize("stem", SVM_FEATURES)
def test_svm_configs_match_spec(stem: str, condition: str) -> None:
    config = _load(stem, condition)
    assert set(config.data.severities) == CONDITIONS[condition]
    color = config.color
    assert color is not None
    assert color.classifier == "svm_rbf"
    assert color.features == SVM_FEATURES[stem]
    assert color.svm.c_values == (0.1, 1.0, 10.0, 100.0)
    assert color.svm.gammas == ("scale", 0.01, 0.1, 1.0)
    assert color.svm.class_weight == "balanced"
    assert config.train.class_weighting == "none"
    assert config.train.sampler == "random"
    assert config.train.augmentation.color_jitter is None
    assert config.train.color_shift_pseudo.mode == "none"


@pytest.mark.parametrize("condition", CONDITIONS)
@pytest.mark.parametrize("stem", THRESHOLDS)
def test_coat_removal_thresholds_match_spec(stem: str, condition: str) -> None:
    color = _load(stem, condition).color
    assert color is not None
    assert color.max_side is None  # 元の解像度で計算する
    assert color.coat_removal is not None
    white, yellow = THRESHOLDS[stem]
    assert color.coat_removal.white.model_dump() == white
    assert color.coat_removal.yellow.model_dump() == yellow


def test_lateral_config_has_no_coat_removal() -> None:
    color = _load("cv_color_svm_lateral", "with_mild").color
    assert color is not None
    assert color.coat_removal is None


# --- 分割の設定が今のモデルとそろっている ---


@pytest.mark.parametrize("condition", CONDITIONS)
@pytest.mark.parametrize("stem", [*RESNET_METHODS, *SVM_FEATURES])
def test_split_settings_match_the_current_model(stem: str, condition: str) -> None:
    config = _load(stem, condition)
    base = load_config(CONFIGS_DIR / f"cv_{condition}.yaml", environ={})
    assert config.split == base.split
    assert config.train.inner_val_ratio == base.train.inner_val_ratio
    assert config.data == base.data


# --- 手元用の設定 ---


@pytest.mark.parametrize("path", sorted(SYNTHETIC_DIR.glob("*.yaml")), ids=lambda p: p.stem)
def test_local_configs_are_small_or_cpu_only(path: Path) -> None:
    config = load_config(path, environ={})
    assert config.model.pretrained is False or config.color is not None
    if config.color is None:
        assert config.train.max_epochs <= 2
        assert config.train.image_size <= 64
        assert config.train.num_workers == 0
