"""設定スキーマのテスト（SPEC_01 基本方針 3・testing ルール必須対象 5）."""

from pathlib import Path

import pytest
from pydantic import ValidationError

from tias_judge_model.schema import (
    DATA_ROOT_ENV_VAR,
    BundleConfig,
    DataConfig,
    ExperimentConfig,
    load_config,
)

REPO_ROOT = Path(__file__).resolve().parents[1]

VALID_YAML = """\
data:
  root: some/data
  manifest: manifest.csv
split:
  seed: 7
  val_ratio: 0.1
  test_ratio: 0.2
  n_folds: 5
"""


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


def test_load_valid_config(tmp_path: Path) -> None:
    config = load_config(_write(tmp_path, VALID_YAML), environ={})
    assert isinstance(config, ExperimentConfig)
    assert config.data.root == Path("some/data")
    assert config.data.manifest_path == Path("some/data") / "manifest.csv"
    assert config.data.images_dir == Path("some/data") / "images"
    assert config.split.seed == 7
    assert config.split.val_ratio == pytest.approx(0.1)
    assert config.split.test_ratio == pytest.approx(0.2)
    assert config.split.n_folds == 5


def test_split_section_is_optional(tmp_path: Path) -> None:
    config = load_config(_write(tmp_path, "data:\n  root: d\n"), environ={})
    assert config.split.n_folds == 5  # SPEC_02: 結論を出すときは 5-fold
    assert config.split.val_ratio + config.split.test_ratio < 1.0


@pytest.mark.parametrize("name", ["synthetic.yaml", "newton.yaml"])
def test_repository_configs_are_valid(name: str) -> None:
    config = load_config(REPO_ROOT / "configs" / name, environ={})
    assert config.split.n_folds == 5


def test_env_var_overrides_yaml_data_root(tmp_path: Path) -> None:
    env_root = tmp_path / "from_env"
    config = load_config(_write(tmp_path, VALID_YAML), environ={DATA_ROOT_ENV_VAR: str(env_root)})
    assert DATA_ROOT_ENV_VAR == "TIAS_DATA_ROOT"
    assert config.data.root == env_root
    assert config.data.manifest_path == env_root / "manifest.csv"


def test_env_var_supplies_root_missing_from_yaml(tmp_path: Path) -> None:
    config = load_config(
        _write(tmp_path, "split:\n  seed: 1\n"), environ={DATA_ROOT_ENV_VAR: "env/root"}
    )
    assert config.data.root == Path("env/root")


def test_yaml_root_used_when_env_var_absent(tmp_path: Path) -> None:
    config = load_config(_write(tmp_path, VALID_YAML), environ={"OTHER": "x"})
    assert config.data.root == Path("some/data")


def test_os_environ_is_used_by_default(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv(DATA_ROOT_ENV_VAR, "from/os/environ")
    config = load_config(_write(tmp_path, VALID_YAML))
    assert config.data.root == Path("from/os/environ")


@pytest.mark.parametrize(
    "split_yaml",
    [
        "  val_ratio: 0.5\n  test_ratio: 0.5\n",  # 合計 1
        "  val_ratio: 0.6\n  test_ratio: 0.5\n",  # 合計 1 超
        "  val_ratio: -0.1\n",
        "  test_ratio: 1.0\n",
        "  n_folds: 1\n",
        "  n_folds: 0\n",
        "  seed: not_a_number\n",
        "  n_foldz: 5\n",  # 未知のキー（綴り間違い）
    ],
)
def test_invalid_split_is_rejected(tmp_path: Path, split_yaml: str) -> None:
    text = "data:\n  root: d\nsplit:\n" + split_yaml
    with pytest.raises(ValidationError):
        load_config(_write(tmp_path, text), environ={})


@pytest.mark.parametrize(
    "text",
    [
        "split:\n  seed: 1\n",  # data が無い
        "data:\n  manifest: m.csv\n",  # data.root が無い
        "data:\n  root: d\n  rooot: e\n",  # data の未知のキー
        "data:\n  root: d\nmodel: convnext\n",  # トップレベルの未知のキー
    ],
)
def test_missing_required_or_unknown_key_is_rejected(tmp_path: Path, text: str) -> None:
    with pytest.raises(ValidationError):
        load_config(_write(tmp_path, text), environ={})


def test_empty_yaml_is_rejected(tmp_path: Path) -> None:
    with pytest.raises(ValidationError):
        load_config(_write(tmp_path, ""), environ={})


def test_non_mapping_yaml_is_rejected(tmp_path: Path) -> None:
    with pytest.raises(ValueError):
        load_config(_write(tmp_path, "- a\n- b\n"), environ={})


# --- data.bundle（TIASDataHub のバンドル） ---

BUNDLE_YAML = "data:\n  bundle:\n    name: tongue_color\n    version: 1\n"
# 実データ用でない設定（手元の合成データ・セグメンテーション・リモート実行）
NON_BUNDLE_CONFIGS = {
    "remote.yaml",
    "synthetic.yaml",
    "cv_synthetic.yaml",
    "color_synthetic.yaml",
    "export/color_synthetic.yaml",
    "seg/eval_newton.yaml",
    "seg/eval_synthetic.yaml",
}
# 手元用の設定のうち合成バンドルを読むもの（実データの tongue_color を読まないこと）
SYNTHETIC_BUNDLE_NAME = "tongue_color_synthetic"
SYNTHETIC_BUNDLE_CONFIGS = {
    f"predecessor/synthetic/{stem}_synthetic.yaml"
    for stem in (
        "cv_pred_resnet34",
        "cv_pred_resnet34_color_shift_real_plus_pseudo",
        "cv_pred_resnet34_color_shift_pseudo_only",
        "cv_color_svm_lateral",
        "cv_color_svm_coat_removed",
        "cv_color_svm_coat_removed_slide",
    )
}
NON_BUNDLE_CONFIGS |= SYNTHETIC_BUNDLE_CONFIGS
# 1 回目のラベルの設定（SPEC_02「1 回目のラベルでの実行」の表）．ディレクトリごとではなく名前で
# 除く（同じディレクトリに別の設定を足すと，実データ用の検査と下の一覧の検査の両方で気づける）
FIRST_ROUND_LABEL_KIND = "tongue_color_first_round"
FIRST_ROUND_BUNDLE_NAME = "tongue_color_first_round"
FIRST_ROUND_SYNTHETIC_BUNDLE_NAME = "tongue_color_first_round_synthetic"
FIRST_ROUND_CONFIGS = {
    f"predecessor_first_round/cv_first_round_{method}_{condition}.yaml"
    for method in (
        "pred_resnet34",
        "pred_resnet34_color_shift_real_plus_pseudo",
        "pred_resnet34_color_shift_pseudo_only",
        "color_svm_lateral",
        "color_svm_coat_removed",
        "color_svm_coat_removed_slide",
    )
    for condition in ("with_mild", "without_mild")
}
FIRST_ROUND_SYNTHETIC_CONFIGS = {
    f"predecessor_first_round/synthetic/cv_first_round_{method}_synthetic.yaml"
    for method in ("pred_resnet34", "color_svm_lateral", "color_svm_coat_removed")
}
NON_BUNDLE_CONFIGS |= FIRST_ROUND_SYNTHETIC_CONFIGS


def _real_data_configs() -> list[str]:
    configs = REPO_ROOT / "configs"
    return sorted(
        rel
        for rel in (p.relative_to(configs).as_posix() for p in configs.rglob("*.yaml"))
        if rel not in NON_BUNDLE_CONFIGS and rel not in FIRST_ROUND_CONFIGS
    )


def test_bundle_config_is_loaded(tmp_path: Path) -> None:
    config = load_config(_write(tmp_path, BUNDLE_YAML), environ={})
    assert config.data.bundle == BundleConfig(name="tongue_color", version=1)
    assert config.data.root is None
    assert config.data.manifest is None
    assert set(config.data.severities) == {"strong", "mild", "normal"}


@pytest.mark.parametrize(
    "data",
    [
        {},  # どちらも無い
        {"severities": ["strong"]},
        {"manifest": "m.csv"},
        {"root": "d", "bundle": {"name": "x", "version": 1}},  # 両方ある
        {"bundle": {"name": "x", "version": 1}, "manifest": "m.csv"},  # bundle と manifest
        {"bundle": {"name": "x", "version": 1, "extra": 1}},  # 未知のキー
        {"bundle": {"name": "x", "versoin": 1}},
        {"bundle": {"name": "x"}},  # 版の省略（暗黙に最新を使わない）
        {"bundle": {"version": 1}},
        {"bundle": {"name": "", "version": 1}},
        {"bundle": {"name": "x", "version": 0}},
        {"bundle": {"name": "x", "version": -1}},
        {"bundle": {"name": "x", "version": "1"}},
        {"bundle": {"name": "x", "version": 1.5}},
        {"bundle": {"name": "x", "version": True}},
    ],
)
def test_invalid_data_source_is_rejected(data: dict) -> None:
    with pytest.raises(ValidationError):
        DataConfig.model_validate(data)


def test_root_config_still_allows_manifest_and_defaults_it() -> None:
    assert DataConfig.model_validate({"root": "d"}).manifest_path == Path("d") / "manifest.csv"
    custom = DataConfig.model_validate({"root": "d", "manifest": "sub/m.csv"})
    assert custom.manifest_path == Path("d") / "sub" / "m.csv"
    assert custom.bundle is None


def test_absolute_manifest_is_used_as_is(tmp_path: Path) -> None:
    absolute = tmp_path / "m.csv"
    data = DataConfig.model_validate({"root": "d", "manifest": str(absolute)})
    assert data.manifest_path == absolute


@pytest.mark.parametrize("attribute", ["images_dir", "manifest_path"])
def test_root_only_paths_are_internal_error_for_bundle(attribute: str) -> None:
    data = DataConfig.model_validate({"bundle": {"name": "x", "version": 1}})
    with pytest.raises(RuntimeError):
        getattr(data, attribute)


@pytest.mark.parametrize("value", ["env/root", ""])
def test_env_var_is_ignored_for_bundle_config(tmp_path: Path, value: str) -> None:
    config = load_config(_write(tmp_path, BUNDLE_YAML), environ={DATA_ROOT_ENV_VAR: value})
    assert config.data.root is None
    assert config.data.bundle is not None


def test_env_var_does_not_hide_root_and_bundle_in_yaml(tmp_path: Path) -> None:
    text = BUNDLE_YAML + "  root: d\n"
    with pytest.raises(ValidationError):
        load_config(_write(tmp_path, text), environ={DATA_ROOT_ENV_VAR: "env/root"})


def test_env_var_applies_when_bundle_is_null(tmp_path: Path) -> None:
    config = load_config(
        _write(tmp_path, "data:\n  bundle: null\n"), environ={DATA_ROOT_ENV_VAR: "env/root"}
    )
    assert config.data.root == Path("env/root")


def test_real_data_config_list_is_not_empty() -> None:
    # 一覧の作り方が壊れて空振りしないことの確認（configs/ の実データ用は 100 件以上ある）
    names = _real_data_configs()
    assert len(names) >= 100
    assert {"newton.yaml", "cv_with_mild.yaml", "export/color_logistic_with_mild.yaml"} <= set(
        names
    )


@pytest.mark.parametrize("name", _real_data_configs())
def test_real_data_configs_use_tongue_color_bundle_v3(name: str) -> None:
    path = REPO_ROOT / "configs" / name
    # tias-remote run は TIAS_DATA_ROOT を常に渡すので，渡した状態で読めること
    for environ in ({}, {DATA_ROOT_ENV_VAR: "/data/on/server"}):
        config = load_config(path, environ=environ)
        assert config.data.bundle == BundleConfig(name="tongue_color", version=3)
        assert config.data.root is None
        assert config.data.manifest is None


@pytest.mark.parametrize(
    "name",
    ["synthetic.yaml", "cv_synthetic.yaml", "color_synthetic.yaml", "export/color_synthetic.yaml"],
)
def test_synthetic_configs_stay_on_data_root(name: str) -> None:
    config = load_config(REPO_ROOT / "configs" / name, environ={})
    assert config.data.bundle is None
    assert config.data.root is not None


def test_synthetic_bundle_config_list_matches_the_directory() -> None:
    # 手元用の設定を足したのに一覧から漏れると，実データ用の検査に回って気づけるが，逆は気づけない
    directory = REPO_ROOT / "configs" / "predecessor" / "synthetic"
    found = {p.relative_to(REPO_ROOT / "configs").as_posix() for p in directory.rglob("*.yaml")}
    assert found == SYNTHETIC_BUNDLE_CONFIGS


@pytest.mark.parametrize("name", sorted(SYNTHETIC_BUNDLE_CONFIGS))
def test_synthetic_bundle_configs_do_not_read_real_data(name: str) -> None:
    config = load_config(REPO_ROOT / "configs" / name, environ={})
    assert config.data.root is None
    assert config.data.bundle is not None
    assert config.data.bundle.name == SYNTHETIC_BUNDLE_NAME
    assert config.data.bundle.name != "tongue_color"


# --- data.severities（SPEC_01「設定ファイル」・SPEC_02「程度（ややあり）の扱い」） ---


def test_severities_default_is_all_three(tmp_path: Path) -> None:
    config = load_config(_write(tmp_path, "data:\n  root: d\n"), environ={})
    assert set(config.data.severities) == {"strong", "mild", "normal"}
    assert len(config.data.severities) == 3


@pytest.mark.parametrize(
    ("value", "expected"),
    [
        ("[strong, normal]", {"strong", "normal"}),  # ややあり除外
        ("[strong, mild, normal]", {"strong", "mild", "normal"}),  # ややあり込み
        ("[normal, strong]", {"strong", "normal"}),  # 記載順は問わない
        ("[mild]", {"mild"}),
    ],
)
def test_valid_severities_are_accepted(tmp_path: Path, value: str, expected: set[str]) -> None:
    config = load_config(_write(tmp_path, f"data:\n  root: d\n  severities: {value}\n"), environ={})
    assert set(config.data.severities) == expected
    assert len(config.data.severities) == len(expected)


@pytest.mark.parametrize(
    "value",
    [
        "[]",  # 空
        "[strong, strong]",  # 重複
        "[strong, normal, strong]",  # 重複
        "[weak]",  # 未知の値
        "[strong, Mild]",  # 大文字違いも未知の値
        "[strong, ややあり]",
    ],
)
def test_invalid_severities_are_rejected(tmp_path: Path, value: str) -> None:
    text = f"data:\n  root: d\n  severities: {value}\n"
    with pytest.raises(ValidationError):
        load_config(_write(tmp_path, text), environ={})


def test_first_round_config_list_matches_the_directory() -> None:
    configs = REPO_ROOT / "configs"
    found = {
        p.relative_to(configs).as_posix()
        for p in (configs / "predecessor_first_round").rglob("*.yaml")
    }
    assert found == FIRST_ROUND_CONFIGS | FIRST_ROUND_SYNTHETIC_CONFIGS
    assert len(FIRST_ROUND_CONFIGS) == 12


@pytest.mark.parametrize("name", sorted(FIRST_ROUND_CONFIGS))
def test_first_round_configs_use_first_round_bundle_v1(name: str) -> None:
    path = REPO_ROOT / "configs" / name
    # tias-remote run は TIAS_DATA_ROOT を常に渡すので，渡した状態で読めること
    for environ in ({}, {DATA_ROOT_ENV_VAR: "/data/on/server"}):
        config = load_config(path, environ=environ)
        assert config.data.bundle == BundleConfig(
            name=FIRST_ROUND_BUNDLE_NAME, version=1, label_kind=FIRST_ROUND_LABEL_KIND
        )
        assert config.data.root is None
        assert config.data.manifest is None


@pytest.mark.parametrize("name", sorted(FIRST_ROUND_SYNTHETIC_CONFIGS))
def test_first_round_synthetic_configs_do_not_read_the_real_bundle(name: str) -> None:
    bundle = load_config(REPO_ROOT / "configs" / name, environ={}).data.bundle
    assert bundle == BundleConfig(
        name=FIRST_ROUND_SYNTHETIC_BUNDLE_NAME, version=1, label_kind=FIRST_ROUND_LABEL_KIND
    )
    assert bundle.name != FIRST_ROUND_BUNDLE_NAME


# --- data.bundle.label_kind（SPEC_01「設定」・SPEC_02「1 回目のラベルでの実行」） ---


def test_label_kind_defaults_to_tongue_color() -> None:
    assert BundleConfig(name="x", version=1).label_kind == "tongue_color"


@pytest.mark.parametrize("kind", ["tongue_color", FIRST_ROUND_LABEL_KIND])
def test_known_label_kinds_are_accepted(kind: str) -> None:
    assert BundleConfig(name="x", version=1, label_kind=kind).label_kind == kind


@pytest.mark.parametrize(
    "kind",
    ["tongue_color_second_round", "first_round", "TONGUE_COLOR", " tongue_color", "", None, 1, []],
    ids=repr,
)
def test_unknown_label_kind_is_rejected(kind: object) -> None:
    with pytest.raises(ValidationError) as excinfo:
        BundleConfig.model_validate({"name": "x", "version": 1, "label_kind": kind})
    assert all("label_kind" in error["loc"] for error in excinfo.value.errors())


def test_unknown_label_kind_in_yaml_is_rejected(tmp_path: Path) -> None:
    text = BUNDLE_YAML + "    label_kind: tongue_colour\n"
    with pytest.raises(ValidationError):
        load_config(_write(tmp_path, text), environ={})


@pytest.mark.parametrize("mode", ["python", "json"])
def test_default_label_kind_is_not_dumped(mode: str) -> None:
    # 書かなくても，既定値を明示しても，config.yaml の記録は過去の run と同じ形
    expected = {"name": "x", "version": 1}
    assert BundleConfig(name="x", version=1).model_dump(mode=mode) == expected
    explicit = BundleConfig(name="x", version=1, label_kind="tongue_color")
    assert explicit.model_dump(mode=mode) == expected


@pytest.mark.parametrize("mode", ["python", "json"])
def test_first_round_label_kind_is_dumped(mode: str) -> None:
    config = BundleConfig(name="x", version=1, label_kind=FIRST_ROUND_LABEL_KIND)
    assert config.model_dump(mode=mode) == {
        "name": "x",
        "version": 1,
        "label_kind": FIRST_ROUND_LABEL_KIND,
    }


def test_label_kind_in_experiment_dump(tmp_path: Path) -> None:
    default = load_config(_write(tmp_path, BUNDLE_YAML), environ={})
    assert default.model_dump(mode="json")["data"]["bundle"] == {
        "name": "tongue_color",
        "version": 1,
    }
    text = BUNDLE_YAML + f"    label_kind: {FIRST_ROUND_LABEL_KIND}\n"
    first_round = load_config(_write(tmp_path, text), environ={})
    assert first_round.model_dump(mode="json")["data"]["bundle"]["label_kind"] == (
        FIRST_ROUND_LABEL_KIND
    )


@pytest.mark.parametrize("kind", ["tongue_color", FIRST_ROUND_LABEL_KIND])
def test_dump_reads_back_as_the_same_bundle(kind: str) -> None:
    config = BundleConfig(name="x", version=1, label_kind=kind)
    assert BundleConfig.model_validate(config.model_dump(mode="json")) == config


@pytest.mark.parametrize("name", ["cv_with_mild.yaml", "newton.yaml"])
def test_existing_configs_dump_without_label_kind(name: str) -> None:
    config = load_config(REPO_ROOT / "configs" / name, environ={})
    assert config.model_dump(mode="json")["data"]["bundle"] == {
        "name": "tongue_color",
        "version": 3,
    }
