"""設定（`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"]
