"""設定スキーマのテスト（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",
}


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
    )


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_v2(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=2)
        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


# --- 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={})
