"""設定（`labremote.yaml`）の検証と環境変数の上書きのテスト（SPEC_02，SPEC_03「接続」）.

TIASJudgeModel の tests/remote/test_config.py の移植．変更（`address`・`user` のキーは無い・
`data_dir` の削除・サーバ名は英数字で始まる・YAML として読めないときの ValueError・`project` が
必須）を足した．
"""

from __future__ import annotations

import re
from pathlib import Path

import pytest
import yaml
from pydantic import ValidationError

from labremote.config import (
    CONFIG_FILE_NAME,
    detect_self_server,
    find_config_path,
    is_self_check_disabled,
    load_remote_config,
    resolve_jump_host,
    resolve_ssh_executable,
)

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


def _base() -> dict:
    return {
        "project": {"name": "DemoProject"},
        "push": {},
        "jump_host": "labpc",
        "connect_timeout_sec": 15,
        "gpu_free": {
            "max_memory_used_mib": 1024,
            "max_utilization_percent": 10,
            "observe_sec": 10,
            "sample_interval_ms": 500,
        },
        "servers": [
            {
                "name": "Newton",
                "priority": 1,
                "remote_dir": "~/work/TongueSegModel",
                "uv": "~/.local/bin/uv",
                "data_ready": True,
            },
            {
                "name": "Archimedes",
                "priority": 2,
                "remote_dir": "~/work/TongueSegModel",
                "uv": "~/.local/bin/uv",
                "data_ready": False,
            },
        ],
    }


def _write(tmp_path: Path, data: dict) -> Path:
    path = tmp_path / "labremote.yaml"
    path.write_text(yaml.safe_dump(data, allow_unicode=True), encoding="utf-8")
    return path


def _invalid(tmp_path: Path, data: dict) -> None:
    with pytest.raises(ValidationError):
        load_remote_config(_write(tmp_path, data))


# ---------------------------------------------------------------------------
# 利用する側のリポジトリの設定（移す元の configs/remote.yaml を読んでいたもの）
# ---------------------------------------------------------------------------


@pytest.mark.skip(
    reason=(
        "LabRemote には利用する側の設定（labremote.yaml）を置かない．利用する側で確かめる"
        "（PLAN_02 の 3-3）"
    )
)
def test_repository_remote_yaml_loads() -> None:
    config = load_remote_config(REPO_ROOT / "configs" / "remote.yaml")
    assert [s.name for s in config.ordered_servers()] == ["Newton", "Archimedes"]
    assert config.jump_host == "labpc"
    for server in config.servers:
        assert server.remote_dir == "~/work/TongueSegModel"
        assert server.uv == "~/.local/bin/uv"


@pytest.mark.skip(
    reason=(
        "LabRemote には利用する側の設定（labremote.yaml）を置かない．利用する側で確かめる"
        "（PLAN_02 の 3-3）"
    )
)
def test_repository_remote_yaml_has_no_address_user_or_key() -> None:
    """アドレス・ユーザー名・鍵の場所はリポジトリに書かない（手元の ~/.ssh/config から決める）."""
    path = REPO_ROOT / "configs" / "remote.yaml"
    config = load_remote_config(path)
    for server in config.servers:
        assert server.address is None
        assert server.user is None
        assert server.ssh_host == server.name
    text = path.read_text(encoding="utf-8")
    raw = yaml.safe_load(text)
    for server in raw["servers"]:
        assert "address" not in server
        assert "user" not in server
    # コメントを含めて，IPv4 アドレス・鍵の場所・ユーザー名・アドレスの指定が無いこと
    assert not re.search(r"\b\d{1,3}(\.\d{1,3}){3}\b", text)
    assert not re.search(r"(?i)identityfile|id_rsa|id_ed25519|id_ecdsa|\.pem\b", text)
    assert not re.search(r"(?m)^\s*(-\s*)?(user|address)\s*:", text)
    assert "carol" not in text


# ---------------------------------------------------------------------------
# 検証
# ---------------------------------------------------------------------------


def test_valid_config_loads(tmp_path: Path) -> None:
    config = load_remote_config(_write(tmp_path, _base()))
    assert [s.name for s in config.servers] == ["Newton", "Archimedes"]
    assert config.jump_host == "labpc"
    assert config.gpu_free.observe_sec == 10
    assert config.servers[1].data_ready is False


def test_jump_host_null_means_direct(tmp_path: Path) -> None:
    data = _base()
    data["jump_host"] = None
    assert load_remote_config(_write(tmp_path, data)).jump_host is None


def test_servers_must_not_be_empty(tmp_path: Path) -> None:
    data = _base()
    data["servers"] = []
    _invalid(tmp_path, data)


def test_servers_are_required(tmp_path: Path) -> None:
    data = _base()
    del data["servers"]
    _invalid(tmp_path, data)


def test_duplicate_server_names_are_rejected(tmp_path: Path) -> None:
    data = _base()
    data["servers"][1]["name"] = "Newton"
    _invalid(tmp_path, data)


def test_duplicate_server_names_ignore_case(tmp_path: Path) -> None:
    # --server は大文字小文字を区別せず照合するため，重複も同じ基準で判定する
    data = _base()
    data["servers"][1]["name"] = "newton"
    _invalid(tmp_path, data)


@pytest.mark.parametrize(
    "name",
    [
        "New ton",
        "Newton;rm",
        "サーバ",
        "a/b",
        "",
        # サーバ名が ssh の接続先になるため，- 始まり等を拒否する
        "-Newton",
        "-oProxyCommand=x",
        "_Newton",
        "Newton\n",
        "New.ton",
        "$(id)",
        "'Newton'",
    ],
)
def test_server_name_characters(tmp_path: Path, name: str) -> None:
    data = _base()
    data["servers"][0]["name"] = name
    _invalid(tmp_path, data)


@pytest.mark.parametrize("name", ["Newton_2", "gpu-01", "A1", "1gpu"])
def test_server_name_allowed_characters(tmp_path: Path, name: str) -> None:
    data = _base()
    data["servers"][0]["name"] = name
    assert load_remote_config(_write(tmp_path, data)).servers[0].name == name


@pytest.mark.parametrize("priority", ["high", 1.5])
def test_priority_must_be_integer(tmp_path: Path, priority: object) -> None:
    data = _base()
    data["servers"][0]["priority"] = priority
    _invalid(tmp_path, data)


@pytest.mark.parametrize(
    ("key", "value", "ok"),
    [
        ("max_memory_used_mib", 0, True),
        ("max_memory_used_mib", -1, False),
        ("max_utilization_percent", 0, True),
        ("max_utilization_percent", 100, True),
        ("max_utilization_percent", -1, False),
        ("max_utilization_percent", 101, False),
        ("observe_sec", 0, True),
        ("observe_sec", 120, True),
        ("observe_sec", -1, False),
        ("observe_sec", 121, False),
        ("sample_interval_ms", 100, True),
        ("sample_interval_ms", 5000, True),
        ("sample_interval_ms", 99, False),
        ("sample_interval_ms", 5001, False),
    ],
)
def test_gpu_free_ranges(tmp_path: Path, key: str, value: int, ok: bool) -> None:
    data = _base()
    data["gpu_free"][key] = value
    if ok:
        assert getattr(load_remote_config(_write(tmp_path, data)).gpu_free, key) == value
    else:
        _invalid(tmp_path, data)


@pytest.mark.parametrize(("value", "ok"), [(1, True), (0, False), (-5, False)])
def test_connect_timeout_at_least_one(tmp_path: Path, value: int, ok: bool) -> None:
    data = _base()
    data["connect_timeout_sec"] = value
    if ok:
        assert load_remote_config(_write(tmp_path, data)).connect_timeout_sec == value
    else:
        _invalid(tmp_path, data)


def test_unknown_top_level_key_is_rejected(tmp_path: Path) -> None:
    data = _base()
    data["jump_hots"] = "labpc"
    _invalid(tmp_path, data)


def test_unknown_server_key_is_rejected(tmp_path: Path) -> None:
    data = _base()
    data["servers"][0]["data_redy"] = True
    _invalid(tmp_path, data)


def test_unknown_gpu_free_key_is_rejected(tmp_path: Path) -> None:
    data = _base()
    data["gpu_free"]["observe_seconds"] = 5
    _invalid(tmp_path, data)


def test_data_dir_of_the_original_is_rejected(tmp_path: Path) -> None:
    # 移植元の data_dir（TIAS_DATA_ROOT）は外した．書かれていれば未知のキーとして拒否する
    data = _base()
    data["servers"][0]["data_dir"] = "~/data/x"
    _invalid(tmp_path, data)


@pytest.mark.parametrize("key", ["name", "priority", "remote_dir"])
def test_missing_required_server_field_is_rejected(tmp_path: Path, key: str) -> None:
    data = _base()
    del data["servers"][0][key]
    _invalid(tmp_path, data)


def test_defaults_of_optional_fields(tmp_path: Path) -> None:
    data = _base()
    for key in ("uv", "data_ready"):
        del data["servers"][0][key]
    for key in ("jump_host", "connect_timeout_sec", "gpu_free"):
        del data[key]
    config = load_remote_config(_write(tmp_path, data))
    server = config.servers[0]
    assert server.uv == "~/.local/bin/uv"
    assert server.data_ready is False
    assert config.jump_host is None
    assert config.connect_timeout_sec == 15
    assert config.gpu_free.model_dump() == {
        "max_memory_used_mib": 1024,
        "max_utilization_percent": 10,
        "observe_sec": 10,
        "sample_interval_ms": 500,
    }


@pytest.mark.parametrize("value", ["yes", 1, "true"])
def test_data_ready_must_be_bool(tmp_path: Path, value: object) -> None:
    data = _base()
    data["servers"][0]["data_ready"] = value
    _invalid(tmp_path, data)


@pytest.mark.parametrize("key", ["remote_dir", "uv"])
@pytest.mark.parametrize("bad", ["", "   ", "~other/x"])
def test_bad_remote_paths_are_rejected(tmp_path: Path, key: str, bad: str) -> None:
    data = _base()
    data["servers"][0][key] = bad
    _invalid(tmp_path, data)


@pytest.mark.parametrize("bad", ["-oProxyCommand=evil", "a b", "j;id", "j\n", "$(id)", ""])
def test_bad_jump_host_is_rejected(tmp_path: Path, bad: str) -> None:
    data = _base()
    data["jump_host"] = bad
    _invalid(tmp_path, data)


def test_missing_file_is_value_error(tmp_path: Path) -> None:
    with pytest.raises(ValueError):
        load_remote_config(tmp_path / "missing.yaml")


def test_malformed_yaml_is_value_error(tmp_path: Path) -> None:
    path = tmp_path / "labremote.yaml"
    path.write_text("servers: [\n  - name: Newton\n", encoding="utf-8")
    with pytest.raises(ValueError):
        load_remote_config(path)


@pytest.mark.parametrize("text", ["- a\n- b\n", "just text\n", ""])
def test_top_level_must_be_mapping(tmp_path: Path, text: str) -> None:
    path = tmp_path / "labremote.yaml"
    path.write_text(text, encoding="utf-8")
    with pytest.raises(ValueError):
        load_remote_config(path)


def test_ordered_servers_and_find_server(tmp_path: Path) -> None:
    data = _base()
    data["servers"][0]["priority"] = 5
    config = load_remote_config(_write(tmp_path, data))
    assert [s.name for s in config.ordered_servers()] == ["Archimedes", "Newton"]
    assert config.find_server("newton").name == "Newton"
    with pytest.raises(ValueError):
        config.find_server("Euler")


def test_with_observe_sec_validates_range(tmp_path: Path) -> None:
    gpu_free = load_remote_config(_write(tmp_path, _base())).gpu_free
    assert gpu_free.with_observe_sec(0).observe_sec == 0
    assert gpu_free.with_observe_sec(3).max_memory_used_mib == 1024
    with pytest.raises(ValidationError):
        gpu_free.with_observe_sec(121)


# ---------------------------------------------------------------------------
# address・user のキーは無い（SPEC_02「`servers`」）
# ---------------------------------------------------------------------------


class TestNoAddressOrUser:
    """アドレス・ユーザー名を書くキーは無く，サーバ名を ssh の Host 名に使う."""

    def test_config_without_address_and_user_loads(self, tmp_path: Path) -> None:
        newton = load_remote_config(_write(tmp_path, _base())).servers[0]
        assert newton.name == "Newton"
        assert not hasattr(newton, "address")
        assert not hasattr(newton, "user")

    @pytest.mark.parametrize("key", ["address", "user"])
    @pytest.mark.parametrize(
        "value", ["Newton", "-oProxyCommand=evil", "a b", "", "h;id", "h\n", "$(id)", "'h'", "h/x"]
    )
    def test_address_or_user_key_is_rejected(self, tmp_path: Path, key: str, value: str) -> None:
        # 書かれていれば，値に関わらず未知のキーとして拒否する（接続の詳細は ~/.ssh/config）
        data = _base()
        data["servers"][0][key] = value
        _invalid(tmp_path, data)


# ---------------------------------------------------------------------------
# 環境変数
# ---------------------------------------------------------------------------


class TestJumpHostEnv:
    def _config(self, tmp_path: Path, jump: str | None = "labpc"):
        data = _base()
        data["jump_host"] = jump
        return load_remote_config(_write(tmp_path, data))

    def test_no_env_uses_config(self, tmp_path: Path) -> None:
        assert resolve_jump_host(self._config(tmp_path), {}) == "labpc"

    def test_env_overrides(self, tmp_path: Path) -> None:
        env = {"LABREMOTE_JUMP": "otherjump"}
        assert resolve_jump_host(self._config(tmp_path), env) == "otherjump"

    @pytest.mark.parametrize("value", ["", "  "])
    def test_empty_env_means_direct(self, tmp_path: Path, value: str) -> None:
        assert resolve_jump_host(self._config(tmp_path), {"LABREMOTE_JUMP": value}) is None

    def test_env_sets_jump_when_config_is_null(self, tmp_path: Path) -> None:
        config = self._config(tmp_path, None)
        assert resolve_jump_host(config, {}) is None
        assert resolve_jump_host(config, {"LABREMOTE_JUMP": "labpc"}) == "labpc"

    @pytest.mark.parametrize("bad", ["-oProxyCommand=evil", "a b", "j;id"])
    def test_bad_env_value_is_rejected(self, tmp_path: Path, bad: str) -> None:
        with pytest.raises(ValueError):
            resolve_jump_host(self._config(tmp_path), {"LABREMOTE_JUMP": bad})

    def test_original_env_name_is_not_used(self, tmp_path: Path) -> None:
        assert resolve_jump_host(self._config(tmp_path), {"TIAS_REMOTE_JUMP": ""}) == "labpc"


class TestSshExecutable:
    def test_env_overrides(self) -> None:
        assert resolve_ssh_executable({"LABREMOTE_SSH": "/opt/ssh"}, "posix") == "/opt/ssh"

    def test_posix_default_is_ssh(self) -> None:
        assert resolve_ssh_executable({}, "posix") == "ssh"


class TestSelfServer:
    def test_hostname_matching_server_name_is_detected(self, tmp_path: Path) -> None:
        config = load_remote_config(_write(tmp_path, _base()))
        server = detect_self_server(config, "Newton")
        assert server is not None and server.name == "Newton"

    def test_hostname_with_domain_and_case_is_detected(self, tmp_path: Path) -> None:
        config = load_remote_config(_write(tmp_path, _base()))
        server = detect_self_server(config, "newton.local")
        assert server is not None and server.name == "Newton"

    def test_other_hostname_is_not_detected(self, tmp_path: Path) -> None:
        config = load_remote_config(_write(tmp_path, _base()))
        assert detect_self_server(config, "my-laptop") is None
        assert detect_self_server(config, "") is None

    def test_allow_self_env(self) -> None:
        assert is_self_check_disabled({"LABREMOTE_ALLOW_SELF": "1"})
        assert not is_self_check_disabled({})
        assert not is_self_check_disabled({"LABREMOTE_ALLOW_SELF": "0"})
        assert not is_self_check_disabled({"TIAS_REMOTE_ALLOW_SELF": "1"})


class TestRenamedEnv:
    """移す元の名前（`TSM_REMOTE_*`）は効かず，`LABREMOTE_*` だけが効く.

    SPEC_01「環境変数」: 手元の環境変数は `LABREMOTE_JUMP`・`LABREMOTE_SSH`・
    `LABREMOTE_ALLOW_SELF`．
    """

    def _config(self, tmp_path: Path):
        return load_remote_config(_write(tmp_path, _base()))

    @pytest.mark.parametrize("value", ["", "otherjump"])
    def test_tsm_remote_jump_is_ignored(self, tmp_path: Path, value: str) -> None:
        assert resolve_jump_host(self._config(tmp_path), {"TSM_REMOTE_JUMP": value}) == "labpc"

    def test_labremote_jump_wins_over_old_name(self, tmp_path: Path) -> None:
        env = {"TSM_REMOTE_JUMP": "oldjump", "LABREMOTE_JUMP": "newjump"}
        assert resolve_jump_host(self._config(tmp_path), env) == "newjump"

    def test_tsm_remote_ssh_is_ignored(self) -> None:
        assert resolve_ssh_executable({"TSM_REMOTE_SSH": "/opt/old-ssh"}, "posix") == "ssh"

    def test_labremote_ssh_wins_over_old_name(self) -> None:
        env = {"TSM_REMOTE_SSH": "/opt/old-ssh", "LABREMOTE_SSH": "/opt/new-ssh"}
        assert resolve_ssh_executable(env, "posix") == "/opt/new-ssh"

    def test_tsm_remote_allow_self_is_ignored(self) -> None:
        assert not is_self_check_disabled({"TSM_REMOTE_ALLOW_SELF": "1"})


# ---------------------------------------------------------------------------
# ルートの探索（SPEC_01「プロジェクトのルートの見つけ方」）
# ---------------------------------------------------------------------------


def _touch_config(directory: Path) -> Path:
    directory.mkdir(parents=True, exist_ok=True)
    path = directory / "labremote.yaml"
    path.write_text("project:\n  name: X\n", encoding="utf-8")
    return path


class TestFindConfigPath:
    """`labremote.yaml` のあるフォルダをルートとし，見つからなければ推測せずに止める."""

    def test_config_file_name(self) -> None:
        """SPEC_02: 設定ファイルは各プロジェクトのルートに置く `labremote.yaml`."""
        assert CONFIG_FILE_NAME == "labremote.yaml"

    def test_config_in_start_directory(self, tmp_path: Path) -> None:
        """SPEC_01: 実行した場所に `labremote.yaml` があれば，そこがルート."""
        config = _touch_config(tmp_path / "proj")
        found = find_config_path(tmp_path / "proj")
        assert found == config.resolve()
        assert found.parent == (tmp_path / "proj").resolve()

    def test_config_in_ancestor(self, tmp_path: Path) -> None:
        """SPEC_01: 無ければ親へたどり，見つかった `labremote.yaml` のあるフォルダがルート."""
        config = _touch_config(tmp_path / "proj")
        start = tmp_path / "proj" / "src" / "pkg" / "deep"
        start.mkdir(parents=True)
        assert find_config_path(start) == config.resolve()

    def test_nearest_config_wins(self, tmp_path: Path) -> None:
        """SPEC_01: 親へたどって最初に見つかったもの（近いほう）を使う."""
        _touch_config(tmp_path / "outer")
        inner = _touch_config(tmp_path / "outer" / "inner")
        start = tmp_path / "outer" / "inner" / "sub"
        start.mkdir()
        assert find_config_path(start) == inner.resolve()
        assert find_config_path(tmp_path / "outer" / "inner") == inner.resolve()

    def test_explicit_config_wins_over_ancestors(self, tmp_path: Path) -> None:
        """SPEC_01: `--config PATH` のときはそのファイルが設定で，そのフォルダがルート."""
        _touch_config(tmp_path / "proj")
        start = tmp_path / "proj" / "sub"
        start.mkdir()
        other = _touch_config(tmp_path / "elsewhere")
        found = find_config_path(start, other)
        assert found == other.resolve()
        assert found.parent == (tmp_path / "elsewhere").resolve()

    def test_explicit_config_with_other_file_name(self, tmp_path: Path) -> None:
        """SPEC_01: `--config PATH` のファイルのあるフォルダがルート（ファイル名は問わない）."""
        _touch_config(tmp_path / "proj")
        other = tmp_path / "cfg" / "custom.yaml"
        other.parent.mkdir()
        other.write_text("project:\n  name: X\n", encoding="utf-8")
        found = find_config_path(tmp_path / "proj", other)
        assert found == other.resolve()
        assert found.parent == (tmp_path / "cfg").resolve()

    def test_explicit_relative_path_is_resolved_from_start(self, tmp_path: Path) -> None:
        """SPEC_01: `--config PATH` は実行した場所からのパスとして解釈する."""
        other = _touch_config(tmp_path / "proj" / "cfg")
        found = find_config_path(tmp_path / "proj", Path("cfg") / "labremote.yaml")
        assert found == other.resolve()

    @pytest.mark.parametrize("kind", ["missing", "directory"])
    def test_explicit_path_that_is_not_a_file_is_error(self, tmp_path: Path, kind: str) -> None:
        """SPEC_01: `--config` のファイルが無ければ，他を探さずエラーで止まる."""
        _touch_config(tmp_path / "proj")
        explicit = tmp_path / "proj" / "nothing.yaml"
        if kind == "directory":
            explicit.mkdir()
        with pytest.raises(ValueError):
            find_config_path(tmp_path / "proj", explicit)

    def test_no_config_anywhere_is_error(self, tmp_path: Path) -> None:
        """SPEC_01: どこにも無ければエラーで止まる（推測でルートを決めない）."""
        start = tmp_path / "a" / "b"
        start.mkdir(parents=True)
        # 前提: tmp_path の祖先に labremote.yaml が無い（あると，このテストは意味を持たない）
        assert not any((d / "labremote.yaml").exists() for d in (start, *start.resolve().parents))
        with pytest.raises(ValueError):
            find_config_path(start)

    def test_other_file_names_are_not_found(self, tmp_path: Path) -> None:
        """SPEC_01: 探すのは `labremote.yaml` だけ（旧 configs/remote.yaml 等で推測しない）."""
        start = tmp_path / "proj"
        (start / "configs").mkdir(parents=True)
        (start / "configs" / "remote.yaml").write_text("x: 1\n", encoding="utf-8")
        (start / "labremote.yml").write_text("x: 1\n", encoding="utf-8")
        with pytest.raises(ValueError):
            find_config_path(start)

    def test_directory_named_like_config_does_not_fall_through(self, tmp_path: Path) -> None:
        """SPEC_01: 推測でルートを決めない（ファイルでない labremote.yaml で上の設定を選ばない）."""
        _touch_config(tmp_path / "outer")
        start = tmp_path / "outer" / "inner"
        (start / "labremote.yaml").mkdir(parents=True)
        with pytest.raises(ValueError):
            find_config_path(start)


# ---------------------------------------------------------------------------
# project（SPEC_02「`project`」）
# ---------------------------------------------------------------------------


class TestProject:
    def test_project_is_required(self, tmp_path: Path) -> None:
        """SPEC_02「`project`」: `project` は必須（name が必須のため）."""
        data = _base()
        del data["project"]
        _invalid(tmp_path, data)

    def test_name_is_required(self, tmp_path: Path) -> None:
        """SPEC_02「`project`」: `name` は必須."""
        data = _base()
        data["project"] = {"git_commit_env": "DEMO_GIT_COMMIT"}
        _invalid(tmp_path, data)

    @pytest.mark.parametrize("project", [None, "DemoProject", ["DemoProject"]])
    def test_project_must_be_mapping(self, tmp_path: Path, project: object) -> None:
        """SPEC_02「`project`」: `project` は `name` 等を持つマッピング."""
        data = _base()
        data["project"] = project
        _invalid(tmp_path, data)

    @pytest.mark.parametrize("name", ["DemoProject", "TongueSegModel", "a", "1x", "a_b-c", "A1"])
    def test_valid_names(self, tmp_path: Path, name: str) -> None:
        """SPEC_02「`project`」: 英数字で始まり，英数字・`_`・`-` だけの名前は通る."""
        data = _base()
        data["project"]["name"] = name
        assert load_remote_config(_write(tmp_path, data)).project.name == name

    @pytest.mark.parametrize(
        "name",
        [
            "",
            "-Demo",
            "_Demo",
            "Demo Project",
            " Demo",
            "Demo/x",
            "Demo\\x",
            "Demo\n",
            "Demo\r\n",
            "Demo.x",
            "../x",
            "Demo;id",
            "$(id)",
            "デモ",
            "Demo\x00",
        ],
    )
    def test_invalid_names_are_rejected(self, tmp_path: Path, name: str) -> None:
        """SPEC_02「`project`」: 英数字で始まり英数字・`_`・`-` だけでない名前はエラー."""
        data = _base()
        data["project"]["name"] = name
        _invalid(tmp_path, data)

    @pytest.mark.parametrize("name", [1, True, None])
    def test_name_must_be_string(self, tmp_path: Path, name: object) -> None:
        """SPEC_02「`project`」: `name` は文字列の名前."""
        data = _base()
        data["project"]["name"] = name
        _invalid(tmp_path, data)

    def test_git_commit_env_is_optional(self, tmp_path: Path) -> None:
        """SPEC_02「`project`」: `git_commit_env` は任意（省略できる）."""
        config = load_remote_config(_write(tmp_path, _base()))
        assert config.project.git_commit_env is None
        assert config.reserved_env_vars() == frozenset(RESERVED)

    def test_unknown_project_key_is_rejected(self, tmp_path: Path) -> None:
        """SPEC_02: 未知のキーは拒否する（`project` の下）."""
        data = _base()
        data["project"]["git_commit_var"] = "DEMO_GIT_COMMIT"
        _invalid(tmp_path, data)


# ---------------------------------------------------------------------------
# project.git_commit_env（SPEC_01「環境変数」，SPEC_02「`project`」）
# ---------------------------------------------------------------------------

RESERVED = ["CUDA_VISIBLE_DEVICES", "CUDA_DEVICE_ORDER", "PYTHONUNBUFFERED", "LABREMOTE_GIT_COMMIT"]


class TestGitCommitEnv:
    @pytest.mark.parametrize("name", ["TSM_GIT_COMMIT", "DEMO_GIT_COMMIT", "_X", "a1"])
    def test_valid_name_is_accepted_and_reserved(self, tmp_path: Path, name: str) -> None:
        """SPEC_01「環境変数」: 指定した名前は，予約の 5 つ目になる."""
        data = _base()
        data["project"]["git_commit_env"] = name
        config = load_remote_config(_write(tmp_path, data))
        assert config.project.git_commit_env == name
        assert config.reserved_env_vars() == frozenset({*RESERVED, name})

    @pytest.mark.parametrize("name", RESERVED)
    def test_reserved_name_is_rejected(self, tmp_path: Path, name: str) -> None:
        """SPEC_01「環境変数」: 予約の名前を git_commit_env に書くとエラー."""
        data = _base()
        data["project"]["git_commit_env"] = name
        _invalid(tmp_path, data)

    @pytest.mark.parametrize(
        "name", ["", "A B", "A=B", "1A", "A\n", "A-B", "A;B", "$A", "A.B", " A", "A\x00"]
    )
    def test_invalid_env_name_is_rejected(self, tmp_path: Path, name: str) -> None:
        """SPEC_01「名前と値の検証」: 環境変数の名前は全体一致で確かめる（末尾の改行も通さない）."""
        data = _base()
        data["project"]["git_commit_env"] = name
        _invalid(tmp_path, data)


# ---------------------------------------------------------------------------
# run.env・servers[].env（SPEC_02「`run`」「`servers`」，SPEC_01「環境変数」「名前と値の検証」）
# ---------------------------------------------------------------------------


def _env_data(where: str, env: dict) -> dict:
    """where が "run" なら run.env に，"server" なら Newton の env に env を書いた設定."""
    data = _base()
    if where == "run":
        data["run"] = {"env": env}
    else:
        data["servers"][0]["env"] = env
    return data


class TestConfigEnv:
    def test_defaults_are_empty(self, tmp_path: Path) -> None:
        """SPEC_02「`run`」: `run.env` の既定は `{}`．`servers[].env` は任意（無ければ空）."""
        config = load_remote_config(_write(tmp_path, _base()))
        assert dict(config.run.env) == {}
        assert all(dict(server.env) == {} for server in config.servers)
        assert config.job_base_env(config.servers[0]) == {}

    def test_run_without_env_key_defaults_to_empty(self, tmp_path: Path) -> None:
        """SPEC_02「`run`」: `run` を書いて `env` を省いても `{}`."""
        data = _base()
        data["run"] = {}
        assert dict(load_remote_config(_write(tmp_path, data)).run.env) == {}

    def test_values_are_loaded(self, tmp_path: Path) -> None:
        """SPEC_02「`run`」「`servers`」: 書いた環境変数が読める."""
        data = _base()
        data["run"] = {"env": {"A": "1"}}
        data["servers"][0]["env"] = {"B": "~/data/x"}
        config = load_remote_config(_write(tmp_path, data))
        assert dict(config.run.env) == {"A": "1"}
        assert dict(config.servers[0].env) == {"B": "~/data/x"}

    def test_server_env_wins_over_run_env(self, tmp_path: Path) -> None:
        """SPEC_02「`run`」: 優先の順は `run.env` → `servers[].env`（後のものが勝つ）."""
        data = _base()
        data["run"] = {"env": {"A": "run", "B": "run"}}
        data["servers"][0]["env"] = {"B": "server", "C": "server"}
        config = load_remote_config(_write(tmp_path, data))
        assert config.job_base_env(config.find_server("Newton")) == {
            "A": "run",
            "B": "server",
            "C": "server",
        }

    def test_server_env_applies_only_to_that_server(self, tmp_path: Path) -> None:
        """SPEC_02「`servers`」: `servers[].env` はそのサーバでだけジョブに渡す."""
        data = _base()
        data["run"] = {"env": {"A": "run"}}
        data["servers"][0]["env"] = {"ONLY_NEWTON": "x"}
        config = load_remote_config(_write(tmp_path, data))
        assert config.job_base_env(config.find_server("Archimedes")) == {"A": "run"}
        assert config.job_base_env(config.find_server("Newton"))["ONLY_NEWTON"] == "x"

    @pytest.mark.parametrize("where", ["run", "server"])
    @pytest.mark.parametrize("name", RESERVED)
    def test_reserved_name_is_rejected_on_load(self, tmp_path: Path, where: str, name: str) -> None:
        """SPEC_02「`run`」: 予約の環境変数はどこにも書けない（設定を読む時点でエラー）."""
        _invalid(tmp_path, _env_data(where, {"OK": "1", name: "x"}))

    @pytest.mark.parametrize("where", ["run", "server", "other_server"])
    def test_git_commit_env_name_is_rejected_on_load(self, tmp_path: Path, where: str) -> None:
        """SPEC_01「環境変数」: `git_commit_env` に書いた名前も予約で，設定に書けない."""
        data = _base()
        data["project"]["git_commit_env"] = "DEMO_GIT_COMMIT"
        env = {"DEMO_GIT_COMMIT": "fake"}
        if where == "run":
            data["run"] = {"env": env}
        elif where == "server":
            data["servers"][0]["env"] = env
        else:
            data["servers"][1]["env"] = env
        _invalid(tmp_path, data)

    def test_other_names_are_not_reserved_without_git_commit_env(self, tmp_path: Path) -> None:
        """SPEC_01「環境変数」: 予約は 4 つ＋設定で指定した名前だけ（指定が無ければ他は書ける）."""
        data = _env_data("run", {"TSM_GIT_COMMIT": "x"})
        assert load_remote_config(_write(tmp_path, data)).run.env["TSM_GIT_COMMIT"] == "x"

    @pytest.mark.parametrize("where", ["run", "server"])
    @pytest.mark.parametrize(
        "name", ["", "A B", "A=B", "1A", "A\n", "A-B", "A;B", "$A", "A.B", "$(id)", "A\x00"]
    )
    def test_invalid_name_is_rejected(self, tmp_path: Path, where: str, name: str) -> None:
        """SPEC_01「名前と値の検証」: 環境変数の名前は全体一致で確かめる."""
        _invalid(tmp_path, _env_data(where, {name: "x"}))

    @pytest.mark.parametrize("where", ["run", "server"])
    @pytest.mark.parametrize("value", ["\x00", "a\x00b", "x\x00"])
    def test_nul_in_value_is_rejected(self, tmp_path: Path, where: str, value: str) -> None:
        """SPEC_01「名前と値の検証」: 値は NUL を拒否する."""
        _invalid(tmp_path, _env_data(where, {"A": value}))

    @pytest.mark.parametrize("where", ["run", "server"])
    def test_shell_special_values_are_kept_as_is(self, tmp_path: Path, where: str) -> None:
        """SPEC_01「名前と値の検証」: 拒否するのは NUL だけで，値はそのまま（引用して渡す）."""
        env = {"A": "x; rm -rf ~", "B": "$(id)", "C": 'it\'s "q"', "D": "a\nb", "E": ""}
        config = load_remote_config(_write(tmp_path, _env_data(where, env)))
        assert config.job_base_env(config.find_server("Newton")) == env

    def test_unknown_run_key_is_rejected(self, tmp_path: Path) -> None:
        """SPEC_02: 未知のキーは拒否する（`run` の下）."""
        data = _base()
        data["run"] = {"envs": {"A": "1"}}
        _invalid(tmp_path, data)

    @pytest.mark.parametrize("where", ["run", "server"])
    @pytest.mark.parametrize("env", [["A=1"], "A=1"])
    def test_env_must_be_mapping(self, tmp_path: Path, where: str, env: object) -> None:
        """SPEC_02「`run`」: `env` は名前と値の対応（`{}` の形）."""
        _invalid(tmp_path, _env_data(where, env))  # type: ignore[arg-type]


class TestDefaultsOfNewFields:
    def test_minimal_config(self, tmp_path: Path) -> None:
        """SPEC_02 の既定: `jump_host` は null，`data_ready` は false，`uv` は既定，`env` は空.

        `push` の節は省略できないため，最小の設定にも `push: {}` を書く（節の中の既定は空）．
        """
        data = {
            "project": {"name": "DemoProject"},
            "push": {},
            "servers": [{"name": "Newton", "priority": 1, "remote_dir": "~/work/x"}],
        }
        config = load_remote_config(_write(tmp_path, data))
        server = config.servers[0]
        assert config.jump_host is None
        assert server.data_ready is False
        assert server.uv == "~/.local/bin/uv"
        assert dict(server.env) == {}
        assert dict(config.run.env) == {}
        assert config.push.exclude_root == ()
        assert config.push.exclude_dirs == ()
        assert config.push.exclude_suffixes == ()
        assert config.push.partial == ()


# ---------------------------------------------------------------------------
# push（SPEC_02「`push`」）
# ---------------------------------------------------------------------------


def _push_data(push: object) -> dict:
    data = _base()
    data["push"] = push
    return data


# 1 つの名前として書けないもの（exclude_root・exclude_dirs・partial の include で共通）
BAD_PUSH_NAMES: list[object] = [
    "a/b",
    "a\\b",
    "data/",
    "*",
    "da*ta",
    "dat?",
    "[d]ata",
    ".",
    "..",
    "",
    " data",
    "data ",
    "data\t",
    "data\n",
    "da\x00ta",
    1,
    True,
    None,
    ["data"],
]

FIXED_DIR_NAMES = [".git", ".venv", ".claude", "__pycache__", ".pytest_cache", ".ruff_cache"]


def _fixed_paths() -> list[str]:
    paths = []
    for name in FIXED_DIR_NAMES:
        paths += [name, f"{name}/x", f"a/{name}/x", f"a/b/{name}", name.upper() + "/x"]
    paths += ["runs", "runs/x", "Runs/x", "labremote.yaml", "labremote.yaml/x", "LabRemote.YAML/x"]
    return paths


class TestPushSection:
    def test_missing_push_is_rejected_with_hint(self, tmp_path: Path) -> None:
        """SPEC_02「`push`」: push の節は省略できない（push: {} と書けばよいことを示す）."""
        data = _base()
        del data["push"]
        with pytest.raises(ValidationError) as excinfo:
            load_remote_config(_write(tmp_path, data))
        assert "push: {}" in str(excinfo.value)

    def test_null_push_is_rejected_with_hint(self, tmp_path: Path) -> None:
        """SPEC_02「`push`」: push: null も省略と同じくエラー."""
        with pytest.raises(ValidationError) as excinfo:
            load_remote_config(_write(tmp_path, _push_data(None)))
        assert "push: {}" in str(excinfo.value)

    def test_empty_push_loads_with_empty_defaults(self, tmp_path: Path) -> None:
        """SPEC_02「`push`」: push: {} は通り，節の中の既定は空."""
        push = load_remote_config(_write(tmp_path, _push_data({}))).push
        assert (push.exclude_root, push.exclude_dirs, push.exclude_suffixes, push.partial) == (
            (),
            (),
            (),
            (),
        )

    def test_values_are_loaded(self, tmp_path: Path) -> None:
        """SPEC_02「`push`」: 4 つのキーを読む（拡張子は小文字にそろえる）."""
        push = load_remote_config(
            _write(
                tmp_path,
                _push_data(
                    {
                        "exclude_root": ["data", "legacy"],
                        "exclude_dirs": ["wandb"],
                        "exclude_suffixes": [".PT", ".tar.gz"],
                        "partial": [{"path": "external/Sub", "include": ["src", "README.md"]}],
                    }
                ),
            )
        ).push
        assert push.exclude_root == ("data", "legacy")
        assert push.exclude_dirs == ("wandb",)
        assert push.exclude_suffixes == (".pt", ".tar.gz")
        assert push.partial[0].path == "external/Sub"
        assert push.partial[0].include == ("src", "README.md")

    @pytest.mark.parametrize("push", ["", "data", ["data"], 1, True])
    def test_push_must_be_mapping(self, tmp_path: Path, push: object) -> None:
        """SPEC_02「`push`」: push は節（キーと値）で書く."""
        _invalid(tmp_path, _push_data(push))

    @pytest.mark.parametrize(
        "push",
        [
            {"exclude": ["data"]},
            {"include": ["data"]},
            {"no_fixed_exclude": True},
            {"fixed_exclude": []},
            {"allow_git": True},
            {"exclude_rot": ["data"]},
            {"partial": [{"path": "a", "include": ["src"], "exclude": ["x"]}]},
            {"partial": [{"path": "a", "include": ["src"], "allow_fixed": True}]},
        ],
    )
    def test_unknown_keys_are_rejected(self, tmp_path: Path, push: dict) -> None:
        """SPEC_02「`push`」: push・partial の下の未知のキー（固定の除外を外すキーを含む）は拒否."""
        _invalid(tmp_path, _push_data(push))

    @pytest.mark.parametrize("key", ["exclude_root", "exclude_dirs"])
    @pytest.mark.parametrize("name", BAD_PUSH_NAMES)
    def test_bad_exclude_names_are_rejected(self, tmp_path: Path, key: str, name: object) -> None:
        """SPEC_02「`push`」: / \\ ワイルドカード . .. 空・前後の空白・NUL・文字列以外は書けない."""
        _invalid(tmp_path, _push_data({key: [name]}))

    @pytest.mark.parametrize("name", BAD_PUSH_NAMES)
    def test_bad_include_names_are_rejected(self, tmp_path: Path, name: object) -> None:
        """SPEC_02「`push`」: partial の include も 1 つの名前だけ（同じ規則）."""
        _invalid(tmp_path, _push_data({"partial": [{"path": "ext/Sub", "include": [name]}]}))

    @pytest.mark.parametrize("key", ["exclude_root", "exclude_dirs", "exclude_suffixes"])
    def test_list_must_not_be_a_bare_string(self, tmp_path: Path, key: str) -> None:
        """SPEC_02「`push`」: 一覧のキーに文字列を 1 つだけ書く書き間違いは拒否."""
        _invalid(tmp_path, _push_data({key: "data" if key != "exclude_suffixes" else ".pt"}))

    @pytest.mark.parametrize(
        "suffix",
        ["pt", "", ".", "..", ".p*", ".p?", ".[p]", "*.pt", ".pt/x", ".p\\t", " .pt", ".pt ", 1],
    )
    def test_bad_suffixes_are_rejected(self, tmp_path: Path, suffix: object) -> None:
        """SPEC_02「`push`」: exclude_suffixes は . で始まる拡張子（.・..・ワイルドカード不可）."""
        _invalid(tmp_path, _push_data({"exclude_suffixes": [suffix]}))

    @pytest.mark.parametrize("suffix", [".pt", ".tar.gz", ".ONNX", ".x-y"])
    def test_good_suffixes_are_accepted(self, tmp_path: Path, suffix: str) -> None:
        """SPEC_02「`push`」: . で始まる拡張子は書ける（小文字にそろえて持つ）."""
        push = load_remote_config(_write(tmp_path, _push_data({"exclude_suffixes": [suffix]}))).push
        assert push.exclude_suffixes == (suffix.lower(),)

    @pytest.mark.parametrize(
        "path",
        [
            "..",
            "../x",
            "a/../b",
            "a/..",
            "/x",
            "/",
            "C:/x",
            "C:\\x",
            "c:x",
            "a\\b",
            "x/*",
            "x/s?c",
            "[x]",
            "",
            "a//b",
            "a/",
            "./a",
            "a/./b",
            " a",
            "a /b",
            "a\x00",
            1,
            None,
        ],
    )
    def test_bad_partial_paths_are_rejected(self, tmp_path: Path, path: object) -> None:
        """SPEC_02「`push`」: partial の path に .. 絶対パス・ワイルドカード・空の部分は書けない."""
        _invalid(tmp_path, _push_data({"partial": [{"path": path, "include": ["src"]}]}))

    @pytest.mark.parametrize("path", _fixed_paths())
    def test_partial_path_inside_fixed_exclusion_is_rejected(
        self, tmp_path: Path, path: str
    ) -> None:
        """SPEC_02「`push`」: 固定の除外の中を指す partial の path は書けない（大小文字問わず）."""
        _invalid(tmp_path, _push_data({"partial": [{"path": path, "include": ["src"]}]}))

    @pytest.mark.parametrize(
        "path", ["src/runs", "a/labremote.yaml", "external/Sub", "runs_old", "a/.gitx"]
    )
    def test_partial_path_outside_fixed_exclusion_is_accepted(
        self, tmp_path: Path, path: str
    ) -> None:
        """SPEC_02「`push`」: runs・labremote.yaml はルートの直下だけ（下の階層の同名は書ける）."""
        push = load_remote_config(
            _write(tmp_path, _push_data({"partial": [{"path": path, "include": ["src"]}]}))
        ).push
        assert push.partial[0].path == path

    @pytest.mark.parametrize(
        ("path_a", "path_b"),
        [
            ("a/b", "a/b"),
            ("a/B", "A/b"),
            ("a", "a/b"),
            ("a/b", "a"),
            ("A", "a/b/c"),
        ],
    )
    def test_duplicate_or_nested_partial_paths_are_rejected(
        self, tmp_path: Path, path_a: str, path_b: str
    ) -> None:
        """SPEC_02「`push`」: 同じ path・一方が他方の中にある path は書けない."""
        partial = [{"path": path_a, "include": ["src"]}, {"path": path_b, "include": ["lib"]}]
        _invalid(tmp_path, _push_data({"partial": partial}))

    def test_disjoint_partial_paths_are_accepted(self, tmp_path: Path) -> None:
        """SPEC_02「`push`」: 重ならない複数の partial は書ける（前方一致の名前は別の場所）."""
        partial = [
            {"path": "ext/a", "include": ["src"]},
            {"path": "ext/ab", "include": ["lib"]},
            {"path": "vendor", "include": []},
        ]
        push = load_remote_config(_write(tmp_path, _push_data({"partial": partial}))).push
        assert [p.path for p in push.partial] == ["ext/a", "ext/ab", "vendor"]


# ---------------------------------------------------------------------------
# results（SPEC_02「`results`」の「書き方と，書けないもの」）
# ---------------------------------------------------------------------------


def _results_data(results: object, *, push: object | None = None) -> dict:
    data = _base()
    data["results"] = results
    if push is not None:
        data["push"] = push
    return data


def _load_results(tmp_path: Path, results: object, *, push: object | None = None):
    return load_remote_config(_write(tmp_path, _results_data(results, push=push))).results


# Windows で別の場所を指しうる名前（dir・files・dirs の path・checkpoints で共通）
WINDOWS_UNSAFE_NAMES: list[str] = [
    "a<b",
    "a>b",
    "a:b",
    'a"b',
    "a|b",
    "a.",
    "a. ",
    "CON",
    "con",
    "nul",
    "Nul",
    "PRN",
    "AUX",
    "COM1",
    "com9",
    "LPT1",
    "LPT9",
    "con.txt",
    "NUL.png",
    "lpt9.tar.gz",
]

# 1 つの名前として書けないもの（pull.files・checkpoints.files・discard.files・checkpoints.dir）
BAD_RESULT_NAMES: list[object] = [
    "a/b",
    "a\\b",
    "/a",
    "*",
    "*.png",
    "a*",
    "a?",
    "[a]",
    ".",
    "..",
    "",
    " a",
    "a ",
    "a\t",
    "a\n",
    "a\x00b",
    "a\x01b",
    "a\x1bb",
    "a\x7fb",
    "a\nb",
    "_remote_logs",
    *WINDOWS_UNSAFE_NAMES,
    1,
    True,
    None,
    ["a"],
    {"name": "a"},
]

# 相対パスとして書けないもの（dir・dirs の path で共通）
BAD_RESULT_PATHS: list[object] = [
    "..",
    "../x",
    "a/..",
    "a/../b",
    "/x",
    "/",
    "C:/x",
    "C:\\x",
    "c:x",
    "\\x",
    "a\\b",
    "*",
    "ru*ns",
    "run?",
    "[r]uns",
    "a/*",
    "./a",
    "a/./b",
    "a//b",
    "a/",
    ".",
    "",
    " a",
    "a /b",
    "a\x00b",
    "a\nb",
    "_remote_logs",
    "_remote_logs/x",
    *WINDOWS_UNSAFE_NAMES,
    *(f"x/{name}" for name in WINDOWS_UNSAFE_NAMES),
    1,
    None,
    ["runs"],
]


class TestResultsDefaults:
    def test_omitted_results_uses_defaults(self, tmp_path: Path) -> None:
        """SPEC_02「`results`」.

        省略したとき dir は runs，checkpoints.dir は checkpoints，一覧は空.
        """
        results = load_remote_config(_write(tmp_path, _base())).results
        assert results.dir == "runs"
        assert results.checkpoints.dir == "checkpoints"
        assert results.pull.files == ()
        assert results.pull.dirs == ()
        assert results.checkpoints.files == ()
        assert results.discard.files == ()
        assert results.discard.dirs == ()

    def test_empty_results_uses_defaults(self, tmp_path: Path) -> None:
        """SPEC_02「`results`」: results: {} も省略と同じ既定になる."""
        results = _load_results(tmp_path, {})
        assert results.dir == "runs"
        assert results.checkpoints.dir == "checkpoints"
        assert (results.pull.files, results.pull.dirs, results.checkpoints.files) == ((), (), ())

    def test_values_are_loaded(self, tmp_path: Path) -> None:
        """SPEC_02「`results`」: 各キーを書いたとおりに読む（名前はそのまま．小文字にしない）."""
        results = _load_results(
            tmp_path,
            {
                "dir": "output/runs",
                "pull": {
                    "files": ["Summary.TXT", "a b.csv"],
                    "dirs": [{"path": "out/Plots", "suffix": ".SVG"}],
                },
                "checkpoints": {"dir": "Weights", "files": ["Final.ckpt"]},
                "discard": {"files": ["trace.bin"], "dirs": [{"path": "debug", "suffix": ".png"}]},
            },
        )
        assert results.dir == "output/runs"
        assert results.pull.files == ("Summary.TXT", "a b.csv")
        assert [(d.path, d.suffix) for d in results.pull.dirs] == [("out/Plots", ".SVG")]
        assert results.checkpoints.dir == "Weights"
        assert results.checkpoints.files == ("Final.ckpt",)
        assert results.discard.files == ("trace.bin",)
        assert [(d.path, d.suffix) for d in results.discard.dirs] == [("debug", ".png")]


class TestResultsDir:
    @pytest.mark.parametrize("value", ["runs", "output/runs", "a/b/c", "out-put/run_s", "my runs"])
    def test_good_dir_is_accepted(self, tmp_path: Path, value: str) -> None:
        """SPEC_02「`results`」: dir はルートからの相対パスで / 区切りで書く."""
        assert _load_results(tmp_path, {"dir": value}).dir == value

    @pytest.mark.parametrize("value", BAD_RESULT_PATHS)
    def test_bad_dir_is_rejected(self, tmp_path: Path, value: object) -> None:
        """SPEC_02「`results`」.

        dir に ..・絶対パス・ワイルドカード・. や空の部分・Windows の名前は書けない.
        """
        _invalid(tmp_path, _results_data({"dir": value}))

    @pytest.mark.parametrize(
        "value",
        [
            ".git",
            ".git/x",
            "a/.venv",
            ".venv/runs",
            ".claude/x",
            "a/__pycache__",
            ".pytest_cache/x",
            "a/b/.ruff_cache",
            ".GIT/x",
            "a/.Venv",
        ],
    )
    def test_dir_inside_fixed_exclusion_is_rejected(self, tmp_path: Path, value: str) -> None:
        """SPEC_02「`results`」.

        dir は固定の除外のフォルダ（.git・.venv・.claude・キャッシュ）の中を指せない.
        """
        _invalid(tmp_path, _results_data({"dir": value}))

    @pytest.mark.parametrize(
        "value",
        ["_remote_logs", "runs/_remote_logs", "_remote_logs/x", "a/_remote_logs/b", "_REMOTE_LOGS"],
    )
    def test_dir_with_remote_logs_is_rejected(self, tmp_path: Path, value: str) -> None:
        """SPEC_02「`results`」: _remote_logs は dir の部分として使えない."""
        _invalid(tmp_path, _results_data({"dir": value}))

    @pytest.mark.parametrize("value", ["labremote.yaml", "labremote.yaml/x", "LabRemote.YAML"])
    def test_dir_pointing_at_config_file_is_rejected(self, tmp_path: Path, value: str) -> None:
        """SPEC_02「`results`」: dir に labremote.yaml を指す場所は書けない."""
        _invalid(tmp_path, _results_data({"dir": value}))


_FILE_LIST_LOCATIONS = ["pull", "checkpoints", "discard"]


def _with_files(where: str, files: list[object]) -> dict:
    return {where: {"files": files}}


class TestResultsNames:
    @pytest.mark.parametrize("where", _FILE_LIST_LOCATIONS)
    @pytest.mark.parametrize("name", BAD_RESULT_NAMES, ids=repr)
    def test_bad_file_name_is_rejected(self, tmp_path: Path, where: str, name: object) -> None:
        """SPEC_02「`results`」.

        files に書けるのは 1 つのファイル名（/・\\・ワイルドカード・.・..・空・空白・NUL・
        制御文字・Windows の名前・_remote_logs・文字列でない値は不可）.
        """
        _invalid(tmp_path, _results_data(_with_files(where, [name])))

    @pytest.mark.parametrize("where", _FILE_LIST_LOCATIONS)
    @pytest.mark.parametrize(
        "name",
        ["a.txt", "a b.txt", ".hidden", "CONSOLE.txt", "COM10", "nul_", "a.b.c", "日本語.txt"],
    )
    def test_good_file_name_is_accepted(self, tmp_path: Path, where: str, name: str) -> None:
        """SPEC_02「`results`」: 1 つのファイル名として書けるもの（予約名に似た名前を含む）."""
        results = _load_results(tmp_path, _with_files(where, [name]))
        assert getattr(results, where).files == (name,)

    @pytest.mark.parametrize("name", BAD_RESULT_NAMES, ids=repr)
    def test_bad_checkpoints_dir_is_rejected(self, tmp_path: Path, name: object) -> None:
        """SPEC_02「`results`」: checkpoints.dir は実験フォルダの直下の 1 つの名前で書く."""
        _invalid(tmp_path, _results_data({"checkpoints": {"dir": name}}))

    @pytest.mark.parametrize("name", ["weights", "ckpt", "model_out"])
    def test_good_checkpoints_dir_is_accepted(self, tmp_path: Path, name: str) -> None:
        """SPEC_02「`results`」: checkpoints.dir に 1 つの名前を書ける."""
        assert _load_results(tmp_path, {"checkpoints": {"dir": name}}).checkpoints.dir == name

    @pytest.mark.parametrize("where", _FILE_LIST_LOCATIONS)
    @pytest.mark.parametrize(
        "files", [["a.txt", "a.txt"], ["a.txt", "A.TXT"], ["x", "y", "X"]], ids=repr
    )
    def test_duplicate_names_are_rejected(
        self, tmp_path: Path, where: str, files: list[str]
    ) -> None:
        """SPEC_02「`results`」: 一覧の中の重複はエラー（小文字にして比べる）."""
        _invalid(tmp_path, _results_data(_with_files(where, files)))


_DIRS_LOCATIONS = ["pull", "discard"]


def _with_dirs(where: str, dirs: list[object]) -> dict:
    return {where: {"dirs": dirs}}


class TestResultsDirPatterns:
    @pytest.mark.parametrize("where", _DIRS_LOCATIONS)
    @pytest.mark.parametrize("item", [{"path": "figs"}, {"suffix": ".png"}, {}], ids=repr)
    def test_path_and_suffix_are_required(self, tmp_path: Path, where: str, item: dict) -> None:
        """SPEC_02「`results`」: dirs は path と suffix の両方を必ず書く."""
        _invalid(tmp_path, _results_data(_with_dirs(where, [item])))

    @pytest.mark.parametrize("where", _DIRS_LOCATIONS)
    @pytest.mark.parametrize(
        "suffix",
        [
            ".tar.gz",
            "..png",
            ".png.",
            ".",
            "png",
            "",
            ".*",
            "*.png",
            ".p?g",
            ".[p]ng",
            " .png",
            ".png ",
            ".p/g",
            ".p\\g",
            ".p:g",
            ".p\x00g",
            ".p\ng",
            1,
            None,
            [".png"],
        ],
        ids=repr,
    )
    def test_bad_suffix_is_rejected(self, tmp_path: Path, where: str, suffix: object) -> None:
        """SPEC_02「`results`」: suffix は . と 1 つの拡張子（.tar.gz・.・ワイルドカードは不可）."""
        _invalid(tmp_path, _results_data(_with_dirs(where, [{"path": "figs", "suffix": suffix}])))

    @pytest.mark.parametrize("where", _DIRS_LOCATIONS)
    @pytest.mark.parametrize("suffix", [".png", ".PNG", ".csv", ".x1", ".jpeg"])
    def test_good_suffix_is_accepted(self, tmp_path: Path, where: str, suffix: str) -> None:
        """SPEC_02「`results`」: suffix は . で始まる 1 つの拡張子で書く."""
        results = _load_results(tmp_path, _with_dirs(where, [{"path": "figs", "suffix": suffix}]))
        assert getattr(results, where).dirs[0].suffix == suffix

    @pytest.mark.parametrize("where", _DIRS_LOCATIONS)
    @pytest.mark.parametrize("path", BAD_RESULT_PATHS, ids=repr)
    def test_bad_path_is_rejected(self, tmp_path: Path, where: str, path: object) -> None:
        """SPEC_02「`results`」.

        dirs の path に書けないものは dir と同じ（Windows の名前・_remote_logs を含む）.
        """
        _invalid(tmp_path, _results_data(_with_dirs(where, [{"path": path, "suffix": ".png"}])))

    @pytest.mark.parametrize("where", _DIRS_LOCATIONS)
    @pytest.mark.parametrize("path", ["figs", "out/plots", "a/b/c", "my figs"])
    def test_good_path_is_accepted(self, tmp_path: Path, where: str, path: str) -> None:
        """SPEC_02「`results`」: dirs の path は実験フォルダからの相対パス（/ 区切り）."""
        results = _load_results(tmp_path, _with_dirs(where, [{"path": path, "suffix": ".png"}]))
        assert getattr(results, where).dirs[0].path == path

    @pytest.mark.parametrize("where", _DIRS_LOCATIONS)
    @pytest.mark.parametrize(
        "pair",
        [
            [("figs", ".png"), ("figs", ".png")],
            [("figs", ".png"), ("Figs", ".png")],
            [("figs", ".png"), ("figs", ".PNG")],
        ],
        ids=repr,
    )
    def test_duplicate_dirs_are_rejected(
        self, tmp_path: Path, where: str, pair: list[tuple[str, str]]
    ) -> None:
        """SPEC_02「`results`」: dirs の中の重複はエラー（小文字にして比べる）."""
        dirs = [{"path": p, "suffix": s} for p, s in pair]
        _invalid(tmp_path, _results_data(_with_dirs(where, dirs)))

    @pytest.mark.parametrize("where", _DIRS_LOCATIONS)
    def test_same_path_with_other_suffix_is_accepted(self, tmp_path: Path, where: str) -> None:
        """SPEC_02「`results`」: path が同じでも suffix が違えば重複ではない."""
        dirs = [{"path": "figs", "suffix": ".png"}, {"path": "figs", "suffix": ".svg"}]
        results = _load_results(tmp_path, _with_dirs(where, dirs))
        assert len(getattr(results, where).dirs) == 2


# 重みの拡張子（push.exclude_suffixes に書いたもの）
WEIGHT_PUSH = {"exclude_suffixes": [".pth", ".onnx", ".tar.gz"]}


class TestResultsWeightsNotInPull:
    @pytest.mark.parametrize(
        "name", ["best.pth", "BEST.PTH", "best.Pth", "ResUNet.onnx", "model.tar.gz", "m.TAR.GZ"]
    )
    def test_pull_file_with_weight_suffix_is_rejected(self, tmp_path: Path, name: str) -> None:
        """SPEC_02「重みを一覧に紛れ込ませない」.

        pull.files に push.exclude_suffixes の拡張子は書けない.
        """
        _invalid(tmp_path, _results_data({"pull": {"files": [name]}}, push=WEIGHT_PUSH))

    @pytest.mark.parametrize("name", ["best.pth.txt", "onnx_notes.md", "a.gz", "a.tar"])
    def test_pull_file_without_weight_suffix_is_accepted(self, tmp_path: Path, name: str) -> None:
        """SPEC_02「重みを一覧に紛れ込ませない」: 拡張子が重みでない名前は書ける."""
        results = _load_results(tmp_path, {"pull": {"files": [name]}}, push=WEIGHT_PUSH)
        assert results.pull.files == (name,)

    @pytest.mark.parametrize("suffix", [".pth", ".PTH", ".onnx", ".gz", ".GZ"])
    def test_pull_dir_suffix_with_weight_suffix_is_rejected(
        self, tmp_path: Path, suffix: str
    ) -> None:
        """SPEC_02「重みを一覧に紛れ込ませない」.

        suffix に重みの拡張子（一方が他方の末尾も）は書けない.
        """
        results = {"pull": {"dirs": [{"path": "figs", "suffix": suffix}]}}
        _invalid(tmp_path, _results_data(results, push=WEIGHT_PUSH))

    @pytest.mark.parametrize("suffix", [".png", ".tar", ".pt"])
    def test_pull_dir_suffix_not_overlapping_is_accepted(self, tmp_path: Path, suffix: str) -> None:
        """SPEC_02「重みを一覧に紛れ込ませない」.

        重なりの無い拡張子は書ける（.pth に対する .pt も）.
        """
        results = {"pull": {"dirs": [{"path": "figs", "suffix": suffix}]}}
        assert _load_results(tmp_path, results, push=WEIGHT_PUSH).pull.dirs[0].suffix == suffix

    @pytest.mark.parametrize(
        ("checkpoints", "path"),
        [
            (None, "checkpoints"),
            (None, "checkpoints/sub"),
            (None, "Checkpoints"),
            ({"dir": "weights"}, "weights"),
            ({"dir": "weights"}, "weights/a/b"),
            ({"dir": "weights"}, "WEIGHTS/a"),
        ],
    )
    def test_pull_dir_path_in_checkpoints_dir_is_rejected(
        self, tmp_path: Path, checkpoints: dict | None, path: str
    ) -> None:
        """SPEC_02「重みを一覧に紛れ込ませない」.

        pull.dirs の path に checkpoints.dir と同じ場所・その中は書けない.
        """
        results: dict = {"pull": {"dirs": [{"path": path, "suffix": ".png"}]}}
        if checkpoints is not None:
            results["checkpoints"] = checkpoints
        _invalid(tmp_path, _results_data(results))

    @pytest.mark.parametrize("path", ["checkpoints2", "a/checkpoints", "figs"])
    def test_pull_dir_path_outside_checkpoints_dir_is_accepted(
        self, tmp_path: Path, path: str
    ) -> None:
        """SPEC_02「重みを一覧に紛れ込ませない」: checkpoints.dir の外の path は書ける."""
        results = {"pull": {"dirs": [{"path": path, "suffix": ".png"}]}}
        assert _load_results(tmp_path, results).pull.dirs[0].path == path

    def test_checkpoints_dir_changed_frees_default_name(self, tmp_path: Path) -> None:
        """SPEC_02「`results`」.

        checkpoints.dir を変えれば，既定の名前 checkpoints は重みの置き場でない.
        """
        results = {
            "pull": {"dirs": [{"path": "checkpoints", "suffix": ".png"}]},
            "checkpoints": {"dir": "weights"},
        }
        assert _load_results(tmp_path, results).pull.dirs[0].path == "checkpoints"

    @pytest.mark.parametrize(
        ("pull", "ckpt"), [("best.onnx", "best.onnx"), ("Best.onnx", "best.onnx")]
    )
    def test_same_name_in_pull_and_checkpoints_is_rejected(
        self, tmp_path: Path, pull: str, ckpt: str
    ) -> None:
        """SPEC_02「重みを一覧に紛れ込ませない」.

        同じ名前を pull.files と checkpoints.files に書けない.
        """
        results = {"pull": {"files": [pull]}, "checkpoints": {"files": [ckpt]}}
        _invalid(tmp_path, _results_data(results))

    @pytest.mark.parametrize(
        ("checkpoints", "name"),
        [(None, "checkpoints"), (None, "Checkpoints"), ({"dir": "weights"}, "weights")],
    )
    def test_pull_file_named_like_checkpoints_dir_is_rejected(
        self, tmp_path: Path, checkpoints: dict | None, name: str
    ) -> None:
        """SPEC_02「重みを一覧に紛れ込ませない」.

        pull.files に checkpoints.dir と同じ名前は書けない.
        """
        results: dict = {"pull": {"files": [name]}}
        if checkpoints is not None:
            results["checkpoints"] = checkpoints
        _invalid(tmp_path, _results_data(results))

    @pytest.mark.parametrize("path", ["figs", "figs/x", "Figs", "FIGS/a/b"])
    def test_pull_dir_path_starting_with_pull_file_name_is_rejected(
        self, tmp_path: Path, path: str
    ) -> None:
        """SPEC_02「重みを一覧に紛れ込ませない」.

        pull.dirs の path の最初の部分に pull.files の名前は書けない.
        """
        results = {"pull": {"files": ["figs"], "dirs": [{"path": path, "suffix": ".png"}]}}
        _invalid(tmp_path, _results_data(results))

    def test_pull_dir_path_with_pull_file_name_later_is_accepted(self, tmp_path: Path) -> None:
        """SPEC_02「重みを一覧に紛れ込ませない」.

        最初の部分でなければ，pull.files と同じ名前を path に書ける.
        """
        results = {"pull": {"files": ["figs"], "dirs": [{"path": "out/figs", "suffix": ".png"}]}}
        assert _load_results(tmp_path, results).pull.dirs[0].path == "out/figs"


class TestResultsPullAndDiscard:
    @pytest.mark.parametrize(("pull", "discard"), [("a.txt", "a.txt"), ("a.txt", "A.TXT")])
    def test_same_file_in_pull_and_discard_is_rejected(
        self, tmp_path: Path, pull: str, discard: str
    ) -> None:
        """SPEC_02「回収と破棄を両立させない」.

        同じ名前を pull.files と discard.files に書けない.
        """
        results = {"pull": {"files": [pull]}, "discard": {"files": [discard]}}
        _invalid(tmp_path, _results_data(results))

    @pytest.mark.parametrize(
        "discard", [("figs", ".png"), ("Figs", ".png"), ("figs", ".PNG")], ids=repr
    )
    def test_same_dir_pattern_in_pull_and_discard_is_rejected(
        self, tmp_path: Path, discard: tuple[str, str]
    ) -> None:
        """SPEC_02「回収と破棄を両立させない」.

        同じ path と suffix の組を pull.dirs と discard.dirs に書けない.
        """
        results = {
            "pull": {"dirs": [{"path": "figs", "suffix": ".png"}]},
            "discard": {"dirs": [{"path": discard[0], "suffix": discard[1]}]},
        }
        _invalid(tmp_path, _results_data(results))

    def test_different_dir_patterns_in_pull_and_discard_are_accepted(self, tmp_path: Path) -> None:
        """SPEC_02「回収と破棄を両立させない」: 組が違えば，pull.dirs と discard.dirs に書ける."""
        results = {
            "pull": {"files": ["a.txt"], "dirs": [{"path": "figs", "suffix": ".png"}]},
            "discard": {"files": ["b.txt"], "dirs": [{"path": "figs", "suffix": ".svg"}]},
        }
        loaded = _load_results(tmp_path, results)
        assert loaded.discard.files == ("b.txt",)
        assert loaded.discard.dirs[0].suffix == ".svg"

    @pytest.mark.parametrize(
        ("checkpoints", "path"),
        [
            (None, "checkpoints"),
            (None, "checkpoints/sub"),
            (None, "CHECKPOINTS"),
            ({"dir": "weights"}, "weights"),
            ({"dir": "weights"}, "weights/x"),
        ],
    )
    def test_discard_dir_path_in_checkpoints_dir_is_rejected(
        self, tmp_path: Path, checkpoints: dict | None, path: str
    ) -> None:
        """SPEC_02「回収と破棄を両立させない」.

        discard.dirs の path に checkpoints.dir と同じ場所・その中は書けない.
        """
        results: dict = {"discard": {"dirs": [{"path": path, "suffix": ".pth"}]}}
        if checkpoints is not None:
            results["checkpoints"] = checkpoints
        _invalid(tmp_path, _results_data(results))


# 「すべて回収する」「検査を飛ばす」ようなキー．どれも未知のキーとして拒否される
LOOSENING_KEYS = [
    "all",
    "include_all",
    "allow",
    "allow_all",
    "skip_check",
    "no_check",
    "pattern",
    "patterns",
    "glob",
    "regex",
    "recursive",
    "suffixes",
    "extra",
    "unsafe",
    "force",
]


class TestResultsUnknownKeys:
    @pytest.mark.parametrize("key", LOOSENING_KEYS)
    @pytest.mark.parametrize("value", [True, "*", ["*"]], ids=repr)
    def test_unknown_key_under_results_is_rejected(
        self, tmp_path: Path, key: str, value: object
    ) -> None:
        """SPEC_02「`results`」: 未知のキーは拒否する（回収を広げるキーは無い）."""
        _invalid(tmp_path, _results_data({key: value}))

    @pytest.mark.parametrize("where", ["pull", "checkpoints", "discard"])
    @pytest.mark.parametrize("key", LOOSENING_KEYS)
    def test_unknown_key_under_lists_is_rejected(
        self, tmp_path: Path, where: str, key: str
    ) -> None:
        """SPEC_02「`results`」: pull・checkpoints・discard の下の未知のキーは拒否する."""
        _invalid(tmp_path, _results_data({where: {key: True}}))

    @pytest.mark.parametrize("where", _DIRS_LOCATIONS)
    @pytest.mark.parametrize("key", [*LOOSENING_KEYS, "depth", "include"])
    def test_unknown_key_in_dirs_item_is_rejected(
        self, tmp_path: Path, where: str, key: str
    ) -> None:
        """SPEC_02「`results`」.

        dirs の要素の下の未知のキーは拒否する（下の階層を対象にするキーは無い）.
        """
        item = {"path": "figs", "suffix": ".png", key: True}
        _invalid(tmp_path, _results_data(_with_dirs(where, [item])))

    @pytest.mark.parametrize("value", ["runs", ["a"], 1, True])
    def test_results_must_be_mapping(self, tmp_path: Path, value: object) -> None:
        """SPEC_02「`results`」: results は節（キーと値の対応）として書く."""
        _invalid(tmp_path, _results_data(value))


class TestResultsDirAndPartial:
    @pytest.mark.parametrize(
        ("results_dir", "path"),
        [
            (None, "runs"),
            (None, "runs/x"),
            (None, "Runs/x"),
            ("output/runs", "output/runs"),
            ("output/runs", "output/runs/x"),
            ("output/runs", "Output/RUNS/x"),
        ],
    )
    def test_partial_in_results_dir_is_rejected(
        self, tmp_path: Path, results_dir: str | None, path: str
    ) -> None:
        """SPEC_02「結果の置き場と送信」.

        push.partial の path に結果の置き場と同じ場所・その中は書けない.
        """
        results = {} if results_dir is None else {"dir": results_dir}
        push = {"partial": [{"path": path, "include": ["src"]}]}
        _invalid(tmp_path, _results_data(results, push=push))

    @pytest.mark.parametrize("path", ["runs", "runs/x", "output/other", "outputs/runs"])
    def test_partial_outside_changed_results_dir_is_accepted(
        self, tmp_path: Path, path: str
    ) -> None:
        """SPEC_02「結果の置き場と送信」: dir を変えれば，既定の runs は結果の置き場でない."""
        push = {"partial": [{"path": path, "include": ["src"]}]}
        config = load_remote_config(
            _write(tmp_path, _results_data({"dir": "output/runs"}, push=push))
        )
        assert config.push.partial[0].path == path


# ---------------------------------------------------------------------------
# run.exclude_groups（SPEC_02「`run`」「`exclude_groups` の書き方」）
# ---------------------------------------------------------------------------


def _groups_data(groups: object) -> dict:
    data = _base()
    data["run"] = {"exclude_groups": groups}
    return data


class TestRunExcludeGroups:
    def test_default_is_empty(self, tmp_path: Path) -> None:
        """SPEC_02「`run`」: `exclude_groups` の既定は `[]`（`run` を省いても，書いても）."""
        assert tuple(load_remote_config(_write(tmp_path, _base())).run.exclude_groups) == ()
        data = _base()
        data["run"] = {}
        assert tuple(load_remote_config(_write(tmp_path, data)).run.exclude_groups) == ()

    @pytest.mark.parametrize(
        "groups",
        [["remote"], ["remote", "dev.tools"], ["a_b-c.d", "X1"], ["dev.tools", "remote"]],
    )
    def test_valid_names_are_kept_in_order(self, tmp_path: Path, groups: list[str]) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 書ける名前は書いた順に持つ."""
        config = load_remote_config(_write(tmp_path, _groups_data(groups)))
        assert tuple(config.run.exclude_groups) == tuple(groups)

    @pytest.mark.parametrize(
        "name",
        [
            "",
            " remote",
            "remote ",
            "re mote",
            "a/b",
            "a\b",
            "a=b",
            "a;b",
            "$a",
            "a$b",
            "'a'",
            '"a"',
            "-x",
            "_x",
            ".x",
            "remote\n",
            "re\x00mote",
            "リモート",
            "remoté",
            "--frozen",
            "-p",
            "--with x",
            "--no-group=x",
        ],
    )
    def test_invalid_names_are_rejected(self, tmp_path: Path, name: str) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 書けない名前・uv の別の引数はエラー."""
        _invalid(tmp_path, _groups_data(["ok", name]))

    @pytest.mark.parametrize("value", [1, 1.5, True, None, ["remote"]])
    def test_non_string_names_are_rejected(self, tmp_path: Path, value: object) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 文字列でない名前はエラー."""
        _invalid(tmp_path, _groups_data([value]))

    @pytest.mark.parametrize("groups", ["remote", {"remote": True}, 1])
    def test_must_be_a_list(self, tmp_path: Path, groups: object) -> None:
        """SPEC_02「`run`」: `exclude_groups` は名前の一覧（1 つの文字列を書くとエラー）."""
        _invalid(tmp_path, _groups_data(groups))

    @pytest.mark.parametrize(
        "groups",
        [
            ["remote", "remote"],
            ["remote", "Remote"],
            ["a_b", "a-b"],
            ["a_b", "a.b"],
            ["a-b", "A.-B"],
            ["x", "remote", "x"],
        ],
    )
    def test_duplicate_names_are_rejected(self, tmp_path: Path, groups: list[str]) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 大小・_ - . だけ違う名前も重複."""
        _invalid(tmp_path, _groups_data(groups))

    @pytest.mark.parametrize("groups", [["remote", "remote2"], ["ab", "a-b"], ["a-b", "a-b-c"]])
    def test_similar_but_different_names_are_accepted(
        self, tmp_path: Path, groups: list[str]
    ) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 重複でない似た名前は通る."""
        config = load_remote_config(_write(tmp_path, _groups_data(groups)))
        assert tuple(config.run.exclude_groups) == tuple(groups)

    def test_value_is_kept_as_written(self, tmp_path: Path) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 比べ方をそろえても，持つ値は書いたまま."""
        config = load_remote_config(_write(tmp_path, _groups_data(["Remote_X", "Dev..Tools"])))
        assert tuple(config.run.exclude_groups) == ("Remote_X", "Dev..Tools")

    @pytest.mark.parametrize("key", ["uv_args", "no_group", "groups", "uv_options", "extra_args"])
    def test_no_key_for_arbitrary_uv_arguments(self, tmp_path: Path, key: str) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 任意の引数を渡すキーは無い."""
        data = _base()
        data["run"] = {key: ["--frozen"]}
        _invalid(tmp_path, data)
