"""ssh 引数とサーバ上で実行するコマンドの組み立てのテスト（SPEC_03「接続」「取得」「run」）.

TIASJudgeModel の tests/remote/test_commands.py の移植．変更（接続先は `host`（ssh の Host 名）
だけ・probe の `@@labremote-user`・`TIAS_DATA_ROOT` の削除・書式の検証は `fullmatch`）と，
シェルの特殊文字を含む引数の引用の確認を足した．

シェルでの解釈は `shlex.split`（POSIX）で確かめる（リモートの bash を起動しない）．
"""

from __future__ import annotations

import shlex
from collections.abc import Callable

import pytest

import labremote.commands as commands_module
from labremote.commands import (
    GIT_COMMIT_ENV_VAR,
    NO_GPU_LABEL,
    PROBE_END_MARKER,
    PROBE_SESSIONS_MARKER,
    PROBE_USER_PREFIX,
    build_job_env,
    build_job_script,
    build_kill_command,
    build_log_exists_command,
    build_logs_command,
    build_probe_command,
    build_pull_list_command,
    build_pull_tar_command,
    build_push_command,
    build_run_command,
    build_ssh_argv,
    format_git_commit,
    job_log_path,
    parse_env_assignment,
    quote_remote_path,
    validate_env_key,
    validate_job_name,
    validate_ssh_token,
)

# シェルが特別に解釈する文字を含む引数（空白・引用符・; ・$()・バッククォート・改行・グロブ等）
NASTY_ARGS = [
    "a b",
    "it's",
    'say "hi"',
    "x; rm -rf ~",
    "$(id)",
    "`id`",
    "$HOME",
    "a\nb",
    "*",
    "a|b&c>d<e",
    "--",
    "",
    "日本語 の 引数",
    "\\",
    "!event",
]


def _argv(jump: str | None, timeout: int = 15) -> list[str]:
    return build_ssh_argv(
        "ssh",
        host="Newton",
        jump_host=jump,
        connect_timeout_sec=timeout,
        remote_command="echo hi",
    )


def _has_option(argv: list[str], value: str) -> bool:
    return any(argv[i] == "-o" and argv[i + 1] == value for i in range(len(argv) - 1))


class TestBuildSshArgv:
    def test_with_jump_host(self) -> None:
        argv = _argv("labpc")
        assert argv[0] == "ssh"
        j = argv.index("-J")
        assert argv[j + 1] == "labpc"
        assert argv[-2] == "Newton"
        assert argv[-1] == "echo hi"
        # 接続先より前にオプションがある
        assert j < argv.index("Newton")

    def test_without_jump_host(self) -> None:
        argv = _argv(None)
        assert "-J" not in argv
        assert argv[-2] == "Newton"

    @pytest.mark.parametrize("jump", ["labpc", None])
    def test_batch_mode_and_timeout_always(self, jump: str | None) -> None:
        argv = _argv(jump, timeout=7)
        assert _has_option(argv, "BatchMode=yes")
        assert _has_option(argv, "ConnectTimeout=7")

    def test_destination_is_host_name_only(self) -> None:
        # ~/.ssh/config の Host 名だけを渡す（アドレス・ユーザー名・鍵は手元の ssh の設定）
        argv = build_ssh_argv(
            "ssh",
            host="Newton",
            jump_host="labpc",
            connect_timeout_sec=15,
            remote_command="true",
        )
        assert argv[-2:] == ["Newton", "true"]
        assert not any("@" in arg for arg in argv[:-1])

    def test_no_stdin_adds_n_and_stdin_omits_it(self) -> None:
        kwargs = {
            "host": "Newton",
            "jump_host": None,
            "connect_timeout_sec": 5,
            "remote_command": "true",
        }
        assert "-n" in build_ssh_argv("ssh", **kwargs)
        assert "-n" not in build_ssh_argv("ssh", stdin=True, **kwargs)

    def test_remote_command_is_single_argument(self) -> None:
        argv = build_ssh_argv(
            "ssh",
            host="h",
            jump_host=None,
            connect_timeout_sec=5,
            remote_command="cd ~/x; echo a b",
        )
        assert argv[-1] == "cd ~/x; echo a b"

    @pytest.mark.parametrize(
        "bad", ["-oProxyCommand=evil", "a b", "", "h\n", "h;id", "$(id)", "h'", "h/x"]
    )
    @pytest.mark.parametrize("field", ["host", "jump_host"])
    def test_rejects_option_like_or_unsafe_destination(self, bad: str, field: str) -> None:
        kwargs = {"host": "h", "jump_host": None}
        kwargs[field] = bad
        with pytest.raises(ValueError):
            build_ssh_argv("ssh", connect_timeout_sec=5, remote_command="true", **kwargs)

    def test_timeout_must_be_positive(self) -> None:
        with pytest.raises(ValueError):
            _argv(None, timeout=0)


class TestValidateSshToken:
    @pytest.mark.parametrize("value", ["Newton", "labpc", "Host_1", "a.b-c", "fe80::1%eth0"])
    def test_valid(self, value: str) -> None:
        assert validate_ssh_token(value, what="x") == value

    @pytest.mark.parametrize("value", ["", "-J", "a b", "a\n", "a\tb", "a;b", "a$b", "a'b"])
    def test_invalid(self, value: str) -> None:
        with pytest.raises(ValueError):
            validate_ssh_token(value, what="x")


class TestQuoteRemotePath:
    def test_tilde_is_expanded_by_remote_shell(self) -> None:
        assert quote_remote_path("~/work/TongueSegModel") == '"$HOME"/work/TongueSegModel'
        assert quote_remote_path("~") == '"$HOME"'

    def test_special_characters_are_quoted(self) -> None:
        quoted = quote_remote_path("~/a b;$(id)")
        assert quoted.startswith('"$HOME"/')
        assert shlex.split(quoted) == ["$HOME/a b;$(id)"]

    def test_absolute_path(self) -> None:
        assert shlex.split(quote_remote_path("/srv/x y")) == ["/srv/x y"]

    @pytest.mark.parametrize("bad", ["", "  ", "~root/x"])
    def test_rejects_empty_and_other_users_home(self, bad: str) -> None:
        with pytest.raises(ValueError):
            quote_remote_path(bad)


class TestBuildProbeCommand:
    def test_queries_listed_in_spec(self) -> None:
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=10, sample_interval_ms=500
        )
        assert "--query-gpu=index,uuid,name,memory.used,memory.total,utilization.gpu" in command
        assert "--query-compute-apps=gpu_uuid,pid,used_memory" in command
        assert "--format=csv,noheader,nounits" in command

    def test_observation_uses_interval_and_duration(self) -> None:
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=10, sample_interval_ms=500
        )
        assert "-lms 500" in command
        assert "timeout 10" in command
        assert "pmon -s u" in command

    def test_observe_zero_does_not_observe(self) -> None:
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=0, sample_interval_ms=500
        )
        assert "-lms" not in command
        assert "pmon" not in command
        assert "--query-gpu=index,uuid,name" in command

    def test_is_single_line(self) -> None:
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=10, sample_interval_ms=500
        )
        assert "\n" not in command

    def test_reports_own_user_before_sessions(self) -> None:
        # 自分の利用者名を id -un で取る（設定の user を省略できるため．移植元との違い）
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=0, sample_interval_ms=500
        )
        assert f"{PROBE_USER_PREFIX}$(id -un" in command
        assert command.index(PROBE_USER_PREFIX) < command.index(PROBE_SESSIONS_MARKER)
        assert command.rstrip().endswith(f"echo '{PROBE_END_MARKER}'")

    def test_markers_use_tsm_prefix(self) -> None:
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=3, sample_interval_ms=500
        )
        assert "@@tias" not in command
        assert "@@labremote-" in command

    @pytest.mark.parametrize(("observe", "interval"), [(-1, 500), (0, 0)])
    def test_rejects_bad_observation(self, observe: int, interval: int) -> None:
        with pytest.raises(ValueError):
            build_probe_command(
                "~/work/x", results_dir="runs", observe_sec=observe, sample_interval_ms=interval
            )


class TestJobSettings:
    @pytest.mark.parametrize("name", ["a", "exp1", "Exp_1-b", "x" * 64, "0"])
    def test_valid_job_names(self, name: str) -> None:
        assert validate_job_name(name) == name

    @pytest.mark.parametrize(
        "name",
        [
            "",
            "_a",
            "-a",
            "a b",
            "a.b",
            "a:b",
            "x" * 65,
            "a/b",
            # 末尾の改行（match と $ の組み合わせでは通ってしまう）
            "exp1\n",
            "..",
            "a..b",
            "a\\b",
            "a'b",
            'a"b',
            "a;b",
            "a$b",
            "$(id)",
            "a\tb",
            "ジョブ",
        ],
    )
    def test_invalid_job_names(self, name: str) -> None:
        with pytest.raises(ValueError):
            validate_job_name(name)

    def test_job_env_contains_selected_gpu_and_extra(self) -> None:
        env = build_job_env(2, ["FOO=bar", "EMPTY="])
        assert env["CUDA_VISIBLE_DEVICES"] == "2"
        assert env["FOO"] == "bar"
        assert env["EMPTY"] == ""

    def test_job_env_value_may_contain_equals_and_specials(self) -> None:
        env = build_job_env(0, ["A=x=y", "B=$(id); rm -rf ~"])
        assert env["A"] == "x=y"
        assert env["B"] == "$(id); rm -rf ~"

    def test_negative_gpu_index_is_rejected(self) -> None:
        with pytest.raises(ValueError):
            build_job_env(-1, [])

    @pytest.mark.parametrize("item", ["NOEQUALS", "=x", "1A=x", "A B=x", "A\n=x", "A-B=x", "$A=x"])
    def test_bad_env_assignment_is_rejected(self, item: str) -> None:
        with pytest.raises(ValueError):
            build_job_env(0, [item])

    @pytest.mark.parametrize("key", ["A", "_x", "TIASDATA_BUNDLES", "a1_B"])
    def test_valid_env_keys(self, key: str) -> None:
        assert validate_env_key(key) == key
        assert parse_env_assignment(f"{key}=v") == (key, "v")

    @pytest.mark.parametrize(
        "key", ["", "1A", "A\n", "A B", "A-B", "A;B", "A$", "A'", "A.B", "A=B", "ＡＢ"]
    )
    def test_invalid_env_keys(self, key: str) -> None:
        with pytest.raises(ValueError):
            validate_env_key(key)

    @pytest.mark.parametrize("item", ["A=x\x00y", "A=\x00", "A=x\x00", "TIASDATA_BUNDLES=a\x00b"])
    def test_nul_in_env_value_is_rejected(self, item: str) -> None:
        with pytest.raises(ValueError):
            parse_env_assignment(item)
        with pytest.raises(ValueError):
            build_job_env(0, [item])

    def test_nul_error_message_names_key(self) -> None:
        with pytest.raises(ValueError, match="NUL"):
            parse_env_assignment("FOO=x\x00y")

    @pytest.mark.parametrize(
        ("item", "expected"),
        [
            ("A=x\ny", ("A", "x\ny")),
            ("A=x\r\ny", ("A", "x\r\ny")),
            ("A=\t", ("A", "\t")),
            ("A=\x01", ("A", "\x01")),
        ],
    )
    def test_newline_and_other_controls_in_value_pass(
        self, item: str, expected: tuple[str, str]
    ) -> None:
        """改行は通る（`python -c` のコードを渡すため．引用して渡す仕様）."""
        assert parse_env_assignment(item) == expected
        assert build_job_env(0, [item])[expected[0]] == expected[1]


class TestGitCommit:
    """`LABREMOTE_GIT_COMMIT`（SPEC_03「run」・SPEC_01「実験の出力」）."""

    def test_env_var_name(self) -> None:
        assert GIT_COMMIT_ENV_VAR == "LABREMOTE_GIT_COMMIT"

    def test_clean_tree_passes_short_hash(self) -> None:
        # git rev-parse --short HEAD の出力（末尾改行付き）
        assert format_git_commit("abc1234\n", dirty=False) == "abc1234"

    def test_dirty_tree_appends_suffix(self) -> None:
        assert format_git_commit("abc1234\n", dirty=True) == "abc1234-dirty"

    @pytest.mark.parametrize(
        "bad",
        [
            "",
            "abc",  # 短すぎる
            "ABC1234",  # 大文字は git の出力ではない
            "abc1234;id",
            "abc 1234",
            "abc1234\nxyz",
            "$(id)",
            "abc1234..",
            "fatal: not a git repository",
            "a" * 41,
        ],
    )
    def test_unexpected_git_output_is_not_passed(self, bad: str) -> None:
        assert format_git_commit(bad, dirty=False) is None
        assert format_git_commit(bad, dirty=True) is None

    def test_job_env_contains_git_commit(self) -> None:
        env = build_job_env(0, [], git_commit="abc1234-dirty")
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234-dirty"

    def test_job_env_without_git_commit_does_not_set_it(self) -> None:
        env = build_job_env(0, [])
        assert "LABREMOTE_GIT_COMMIT" not in env

    @pytest.mark.parametrize("git_commit", ["abc1234", None])
    def test_env_option_cannot_override_git_commit(self, git_commit: str | None) -> None:
        # git が使えず渡さないときも --env で指定させない（実験の記録を迂回させないため）
        with pytest.raises(ValueError):
            build_job_env(0, ["LABREMOTE_GIT_COMMIT=fake"], git_commit=git_commit)


class TestReservedEnv:
    @pytest.mark.parametrize(
        "key",
        [
            "CUDA_VISIBLE_DEVICES",
            "CUDA_DEVICE_ORDER",
            "PYTHONUNBUFFERED",
            "LABREMOTE_GIT_COMMIT",
        ],
    )
    @pytest.mark.parametrize("gpu_index", [0, None])
    @pytest.mark.parametrize("git_commit", ["abc1234", None])
    def test_reserved_keys_cannot_be_overridden(
        self, key: str, gpu_index: int | None, git_commit: str | None
    ) -> None:
        with pytest.raises(ValueError):
            build_job_env(gpu_index, [f"{key}=x"], git_commit=git_commit)

    def test_reserved_key_rejected_even_after_other_keys(self) -> None:
        with pytest.raises(ValueError):
            build_job_env(0, ["FOO=1", "CUDA_VISIBLE_DEVICES=0,1"])

    def test_tias_data_root_is_no_longer_special(self) -> None:
        # 移植元の TIAS_DATA_ROOT は外した（TongueSegModel はバンドルだけを読む．SPEC_03）
        env = build_job_env(0, ["TIASDATA_BUNDLES=data/synthetic"])
        assert env["TIASDATA_BUNDLES"] == "data/synthetic"
        assert "TIAS_DATA_ROOT" not in env

    def test_fixed_values(self) -> None:
        env = build_job_env(3, [], git_commit="abc1234")
        assert env["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID"
        assert env["PYTHONUNBUFFERED"] == "1"
        assert env["CUDA_VISIBLE_DEVICES"] == "3"


def _script(
    gpu_index: int | None, command: list[str] | None = None, extra: list[str] | None = None
) -> str:
    return build_job_script(
        "~/work/TongueSegModel",
        "train1",
        command or ["tsm-train", "--config", "configs/synthetic-gpu.yaml"],
        uv_path="~/.local/bin/uv",
        server_name="Newton",
        gpu_index=gpu_index,
        env=build_job_env(gpu_index, extra or [], git_commit="abc1234"),
        path_env={},
        results_dir="runs",
    )


class TestCpuJob:
    """`run --cpu`（SPEC_03「run」）.

    CUDA_VISIBLE_DEVICES を空文字で渡し，ログの開始行の GPU は「なし（CPU）」とする．
    """

    def test_cpu_job_env_hides_gpus(self) -> None:
        env = build_job_env(None, ["FOO=bar"], git_commit="abc1234")
        assert "CUDA_VISIBLE_DEVICES" in env
        assert env["CUDA_VISIBLE_DEVICES"] == ""
        assert env["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID"
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234"
        assert env["FOO"] == "bar"

    def test_cpu_job_log_header_says_no_gpu(self) -> None:
        script = _script(None)
        assert f"gpu={NO_GPU_LABEL}" in script
        assert "gpu=なし（CPU）" in script
        assert "gpu=None" not in script
        # 空文字として export する（未設定ではなく空にして GPU を見えなくする）
        assert "export CUDA_VISIBLE_DEVICES=''" in script

    def test_gpu_job_log_header_has_index(self) -> None:
        script = _script(1)
        assert "gpu=1" in script
        assert "なし（CPU）" not in script
        assert "export CUDA_VISIBLE_DEVICES=1" in script
        assert "export LABREMOTE_GIT_COMMIT=abc1234" in script


def _uv_run_args(script: str) -> list[str]:
    """ジョブ本体のスクリプトから，`uv run` に渡る引数（シェルが解釈した後）を取り出す."""
    tokens = shlex.split(script)
    start = tokens.index("$HOME/.local/bin/uv") + 1
    assert tokens[start] == "run"
    end = tokens.index("<", start)
    return tokens[start + 1 : end]


class TestJobScriptQuoting:
    """シェルの特殊文字を含む引数が，そのまま 1 つの引数として `uv run` に渡ること."""

    def test_plain_command(self) -> None:
        script = _script(0)
        assert _uv_run_args(script) == ["tsm-train", "--config", "configs/synthetic-gpu.yaml"]

    @pytest.mark.parametrize("arg", NASTY_ARGS)
    def test_each_nasty_argument_is_one_word(self, arg: str) -> None:
        command = ["tsm-train", "--config", arg]
        assert _uv_run_args(_script(0, command)) == command

    def test_all_nasty_arguments_together(self) -> None:
        command = ["tsm-train", *NASTY_ARGS]
        assert _uv_run_args(_script(0, command)) == command

    def test_env_values_are_quoted(self) -> None:
        value = "x'; touch /tmp/pwned; echo '$(id)"
        tokens = shlex.split(_script(0, extra=[f"FOO={value}"]))
        assert f"FOO={value};" in tokens or f"FOO={value}" in tokens

    def test_script_runs_in_remote_dir_and_logs(self) -> None:
        script = _script(0)
        assert script.startswith('cd "$HOME"/work/TongueSegModel || ')
        assert "runs/_remote_logs/train1.log" in script
        assert "rc=${PIPESTATUS[0]}" in script
        assert "< /dev/null" in script
        assert "\n" not in script

    def test_path_is_extended_with_uv_dir(self) -> None:
        script = _script(0)
        assert 'export PATH="$(dirname -- "$HOME"/.local/bin/uv)":"$HOME/.local/bin:$PATH"' in (
            script
        )

    def test_exports_required_env(self) -> None:
        script = _script(2)
        for statement in [
            "export CUDA_DEVICE_ORDER=PCI_BUS_ID",
            "export CUDA_VISIBLE_DEVICES=2",
            "export PYTHONUNBUFFERED=1",
            "export LABREMOTE_GIT_COMMIT=abc1234",
        ]:
            assert statement in script

    def test_empty_command_is_rejected(self) -> None:
        with pytest.raises(ValueError):
            build_job_script(
                "~/w",
                "j",
                [],
                uv_path="~/.local/bin/uv",
                server_name="Newton",
                gpu_index=0,
                env={},
                path_env={},
                results_dir="runs",
            )

    @pytest.mark.parametrize("name", ["a b", "x;id", "j\n", "-j"])
    def test_bad_job_name_is_rejected(self, name: str) -> None:
        with pytest.raises(ValueError):
            build_job_script(
                "~/w",
                name,
                ["true"],
                uv_path="~/.local/bin/uv",
                server_name="Newton",
                gpu_index=0,
                env={},
                path_env={},
                results_dir="runs",
            )

    @pytest.mark.parametrize("key", ["A B", "A;id", "1A", "A\n"])
    def test_bad_env_key_in_mapping_is_rejected(self, key: str) -> None:
        with pytest.raises(ValueError):
            build_job_script(
                "~/w",
                "j",
                ["true"],
                uv_path="~/.local/bin/uv",
                server_name="Newton",
                gpu_index=0,
                env={key: "v"},
                path_env={},
                results_dir="runs",
            )


class TestRunCommand:
    def test_job_script_round_trips_through_tmux_and_bash_c(self) -> None:
        """tmux → `bash -c` の 2 段の引用を外すと，元のジョブ本体に戻る."""
        script = _script(0, ["tsm-train", *NASTY_ARGS])
        command = build_run_command("~/work/TongueSegModel", "train1", script, results_dir="runs")
        tokens = shlex.split(command)
        i = tokens.index("new-session")
        assert tokens[i : i + 7] == [
            "new-session",
            "-d",
            "-s",
            "train1",
            "-c",
            "$PWD",
            tokens[i + 6],
        ]
        inner = shlex.split(tokens[i + 6])
        assert inner == ["bash", "-c", script]

    def test_refuses_existing_session_with_exact_match(self) -> None:
        command = build_run_command("~/w", "train1", "true", results_dir="runs")
        # = を前置して完全一致（前方一致で別のジョブを選ばない）
        assert "tmux has-session -t =train1 " in command
        assert "exit 91" in command

    @pytest.mark.parametrize("name", ["a b", "x;id", "j\n", ""])
    def test_bad_name_is_rejected(self, name: str) -> None:
        with pytest.raises(ValueError):
            build_run_command("~/w", name, "true", results_dir="runs")


class TestOtherCommands:
    def test_push_extracts_into_remote_dir(self) -> None:
        assert build_push_command("~/work/TongueSegModel") == (
            'mkdir -p "$HOME"/work/TongueSegModel && tar -xf - -C "$HOME"/work/TongueSegModel'
        )

    def test_push_quotes_remote_dir(self) -> None:
        tokens = shlex.split(build_push_command("/srv/a b;id"))
        assert tokens == [
            "mkdir",
            "-p",
            "/srv/a b;id",
            "&&",
            "tar",
            "-xf",
            "-",
            "-C",
            "/srv/a b;id",
        ]

    def test_logs_command(self) -> None:
        command = build_logs_command("~/w", "train1", results_dir="runs", lines=50, follow=False)
        assert "tail -n 50 runs/_remote_logs/train1.log" in command
        follow = build_logs_command("~/w", "train1", results_dir="runs", lines=10, follow=True)
        assert "-F" in follow and "cat >/dev/null" in follow

    def test_logs_rejects_negative_lines_and_bad_name(self) -> None:
        with pytest.raises(ValueError):
            build_logs_command("~/w", "train1", results_dir="runs", lines=-1, follow=False)
        with pytest.raises(ValueError):
            build_logs_command("~/w", "a;b", results_dir="runs", lines=1, follow=False)

    def test_log_exists_and_kill_validate_name(self) -> None:
        for build in (build_log_exists_command, build_kill_command):
            with pytest.raises(ValueError):
                build("~/w", "x$(id)", results_dir="runs")
        assert "tmux kill-session -t =train1" in build_kill_command(
            "~/w", "train1", results_dir="runs"
        )
        assert job_log_path("train1", results_dir="runs") == "runs/_remote_logs/train1.log"

    def test_pull_list_command_quotes_run_id_and_refuses_links(self) -> None:
        command = build_pull_list_command(
            "~/work/TongueSegModel", "20261119-120000_x_abc1234", results_dir="runs"
        )
        assert 'cd "$HOME"/work/TongueSegModel/runs' in command
        assert "[ -L 20261119-120000_x_abc1234 ]" in command
        assert "exit 94" in command
        assert "! -type d -printf '%y %p\\0'" in command

    def test_pull_tar_reads_only_given_names(self) -> None:
        command = build_pull_tar_command("~/work/TongueSegModel", results_dir="runs")
        assert "tar --null --no-recursion -T - -cf -" in command


# ---------------------------------------------------------------------------
# 名前（SPEC_01「環境変数」・SPEC_03「サブコマンド」）
# ---------------------------------------------------------------------------

# 移す元（tsm-remote）の名前．組み立てた結果に残っていないことを確かめる
OLD_NAMES = ["tsm-remote", "tsm_remote", "@@tsm-", "TSM_"]


def _built_commands() -> dict[str, str]:
    """サーバで実行するコマンドを一通り組み立てる（ジョブのコマンドは古い名前を含まないもの）."""
    remote_dir = "~/work/proj"
    script = build_job_script(
        remote_dir,
        "train1",
        ["python", "-m", "train"],
        uv_path="~/.local/bin/uv",
        server_name="Newton",
        gpu_index=0,
        env=build_job_env(0, [], git_commit="abc1234"),
        path_env={},
        results_dir="runs",
    )
    return {
        "probe": build_probe_command(
            remote_dir, results_dir="runs", observe_sec=3, sample_interval_ms=500
        ),
        "push": build_push_command(remote_dir),
        "job_script": script,
        "run": build_run_command(remote_dir, "train1", script, results_dir="runs"),
        "log_exists": build_log_exists_command(remote_dir, "train1", results_dir="runs"),
        "logs": build_logs_command(remote_dir, "train1", results_dir="runs", lines=50, follow=True),
        "kill": build_kill_command(remote_dir, "train1", results_dir="runs"),
        "pull_list": build_pull_list_command(
            remote_dir, "20261119-120000_x_abc1234", results_dir="runs"
        ),
        "pull_tar": build_pull_tar_command(remote_dir, results_dir="runs"),
    }


class TestNaming:
    @pytest.mark.parametrize("kind", list(_built_commands()))
    def test_built_commands_have_no_old_names(self, kind: str) -> None:
        # SPEC_01「全体像」: コマンドの名前は labremote（サーバの目印・エラーの接頭辞も含む）
        command = _built_commands()[kind]
        for old in OLD_NAMES:
            assert old not in command, f"{kind} に {old!r} が残っている"

    @pytest.mark.parametrize("kind", ["run", "logs", "kill"])
    def test_remote_error_messages_use_labremote_prefix(self, kind: str) -> None:
        # SPEC_01「全体像」: サーバ側のエラーメッセージの接頭辞も labremote
        assert "'labremote: " in _built_commands()[kind]

    def test_probe_markers_all_use_labremote_prefix(self) -> None:
        # SPEC_01「全体像」: サーバの出力の目印は @@labremote-
        markers = {
            name: value
            for name, value in vars(commands_module).items()
            if name.startswith("PROBE_") and isinstance(value, str) and value.startswith("@@")
        }
        assert len(markers) >= 10
        for name, marker in markers.items():
            assert marker.startswith("@@labremote-"), name

    def test_job_env_has_no_old_git_commit_name(self) -> None:
        # SPEC_01「環境変数」: ジョブへ渡す git のハッシュは LABREMOTE_GIT_COMMIT
        env = build_job_env(0, [], git_commit="abc1234")
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234"
        assert "TSM_GIT_COMMIT" not in env
        assert not [key for key in env if key.startswith("TSM_")]

    def test_job_script_exports_new_git_commit_name_only(self) -> None:
        # SPEC_01「環境変数」: ジョブへ渡す git のハッシュは LABREMOTE_GIT_COMMIT
        script = _built_commands()["job_script"]
        assert "export LABREMOTE_GIT_COMMIT=abc1234" in script
        assert "TSM_GIT_COMMIT" not in script

    def test_old_git_commit_name_is_not_reserved(self) -> None:
        # SPEC_01「環境変数」: 予約は CUDA_VISIBLE_DEVICES・CUDA_DEVICE_ORDER・PYTHONUNBUFFERED・
        # LABREMOTE_GIT_COMMIT の 4 つだけ．古い名前は普通の変数としてそのまま渡る
        env = build_job_env(0, ["TSM_GIT_COMMIT=x"], git_commit="abc1234")
        assert env["TSM_GIT_COMMIT"] == "x"
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234"


# ---------------------------------------------------------------------------
# git_commit_env と設定由来の環境変数（SPEC_01「環境変数」「名前と値の検証」，SPEC_02「`run`」）
# ---------------------------------------------------------------------------

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


def _exports(script: str) -> dict[str, str]:
    """ジョブ本体のスクリプトを POSIX シェルの規則で区切り，`export K=V` の K と V を取り出す.

    `;` を区切りとして扱うため，値が引用されていなければ `;` で別のコマンドに割れて
    元の値と一致しない．
    """
    lexer = shlex.shlex(script, posix=True, punctuation_chars=True)
    lexer.whitespace_split = True
    tokens = list(lexer)
    found: dict[str, str] = {}
    for i, token in enumerate(tokens[:-1]):
        if token == "export" and "=" in tokens[i + 1]:
            key, _, value = tokens[i + 1].partition("=")
            found[key] = value
            # export の直後は区切り（;）でなければならない（値の一部が別の語として残らない）
            assert tokens[i + 2] == ";"
    return found


class TestGitCommitEnvName:
    def test_same_value_is_passed_under_both_names(self) -> None:
        """SPEC_01「環境変数」: git_commit_env の名前で LABREMOTE_GIT_COMMIT と同じ値を渡す."""
        env = build_job_env(0, [], git_commit="abc1234-dirty", git_commit_env="DEMO_GIT_COMMIT")
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234-dirty"
        assert env["DEMO_GIT_COMMIT"] == "abc1234-dirty"

    def test_without_git_commit_env_only_labremote_name(self) -> None:
        """SPEC_02「`project`」: git_commit_env を指定しなければ LABREMOTE_GIT_COMMIT だけ."""
        env = build_job_env(0, [], git_commit="abc1234")
        assert [k for k, v in env.items() if v == "abc1234"] == ["LABREMOTE_GIT_COMMIT"]

    @pytest.mark.parametrize("git_commit", ["abc1234", None])
    def test_env_option_cannot_override_git_commit_env(self, git_commit: str | None) -> None:
        """SPEC_01「環境変数」: git_commit_env の名前は予約で，`--env` では指定できない."""
        with pytest.raises(ValueError):
            build_job_env(
                0,
                ["FOO=1", "DEMO_GIT_COMMIT=fake"],
                git_commit=git_commit,
                git_commit_env="DEMO_GIT_COMMIT",
            )

    @pytest.mark.parametrize("git_commit", ["abc1234", None])
    def test_base_env_cannot_override_git_commit_env(self, git_commit: str | None) -> None:
        """SPEC_01「環境変数」: git_commit_env の名前は予約で，設定でも指定できない."""
        with pytest.raises(ValueError):
            build_job_env(
                0,
                [],
                git_commit=git_commit,
                git_commit_env="DEMO_GIT_COMMIT",
                base_env={"DEMO_GIT_COMMIT": "fake"},
            )

    @pytest.mark.parametrize("name", RESERVED_NAMES)
    def test_reserved_name_as_git_commit_env_is_rejected(self, name: str) -> None:
        """SPEC_01「環境変数」: 予約の名前は git_commit_env にできない."""
        with pytest.raises(ValueError):
            build_job_env(0, [], git_commit="abc1234", git_commit_env=name)

    @pytest.mark.parametrize("name", ["", "A B", "A=B", "1A", "A\n", "A;B", "$(id)"])
    def test_invalid_git_commit_env_is_rejected(self, name: str) -> None:
        """SPEC_01「名前と値の検証」: 環境変数の名前は全体一致で確かめる."""
        with pytest.raises(ValueError):
            build_job_env(0, [], git_commit="abc1234", git_commit_env=name)

    def test_script_exports_both_names(self) -> None:
        """SPEC_01「環境変数」: 両方の名前がジョブのスクリプトで export される."""
        env = build_job_env(1, [], git_commit="abc1234", git_commit_env="DEMO_GIT_COMMIT")
        script = build_job_script(
            "~/work/x",
            "train1",
            ["python"],
            uv_path="~/.local/bin/uv",
            server_name="Newton",
            gpu_index=1,
            env=env,
            path_env={},
            results_dir="runs",
        )
        exports = _exports(script)
        assert exports["LABREMOTE_GIT_COMMIT"] == "abc1234"
        assert exports["DEMO_GIT_COMMIT"] == "abc1234"


class TestBaseEnv:
    def test_base_env_is_passed(self) -> None:
        """SPEC_02「`run`」: 設定の環境変数がジョブに渡る."""
        env = build_job_env(0, [], base_env={"A": "1", "B": "~/data"})
        assert env["A"] == "1"
        assert env["B"] == "~/data"

    def test_env_option_wins_over_base_env(self) -> None:
        """SPEC_02「`run`」: `--env` で同じ名前を指定すると `--env` が優先される."""
        env = build_job_env(0, ["A=cli"], base_env={"A": "config", "B": "config"})
        assert env["A"] == "cli"
        assert env["B"] == "config"

    def test_fixed_values_are_not_changed_by_base_env(self) -> None:
        """SPEC_01「環境変数」: 予約の値は設定の環境変数があっても変わらない."""
        env = build_job_env(2, [], git_commit="abc1234", base_env={"A": "1"})
        assert env["CUDA_VISIBLE_DEVICES"] == "2"
        assert env["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID"
        assert env["PYTHONUNBUFFERED"] == "1"
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234"

    @pytest.mark.parametrize("name", RESERVED_NAMES)
    @pytest.mark.parametrize("gpu_index", [0, None])
    @pytest.mark.parametrize("git_commit", ["abc1234", None])
    def test_reserved_name_in_base_env_is_rejected(
        self, name: str, gpu_index: int | None, git_commit: str | None
    ) -> None:
        """SPEC_01「名前と値の検証」: 予約の環境変数は設定でも上書きできない."""
        with pytest.raises(ValueError):
            build_job_env(gpu_index, [], git_commit=git_commit, base_env={"A": "1", name: "x"})

    @pytest.mark.parametrize("name", ["", "A B", "A=B", "1A", "A\n", "A-B", "$(id)"])
    def test_invalid_name_in_base_env_is_rejected(self, name: str) -> None:
        """SPEC_01「名前と値の検証」: 環境変数の名前は全体一致で確かめる."""
        with pytest.raises(ValueError):
            build_job_env(0, [], base_env={name: "x"})

    @pytest.mark.parametrize("value", ["\x00", "a\x00b"])
    def test_nul_in_base_env_value_is_rejected(self, value: str) -> None:
        """SPEC_01「名前と値の検証」: 値の NUL を拒否する."""
        with pytest.raises(ValueError):
            build_job_env(0, [], base_env={"A": value})


# 値として渡すシェルの特殊文字（空白・;・$()・引用符・改行等）
NASTY_VALUES = {
    "SPACE": "a b",
    "SEMI": "x; touch pwned",
    "SUBST": "$(id)",
    "BACKTICK": "`id`",
    "SQUOTE": "it's",
    "DQUOTE": 'say "hi"',
    "NEWLINE": "a\nrm -rf ~",
    "VAR": "$HOME",
    "TILDE": "~/data",
    "PIPE": "a|b&c>d<e",
    "EMPTY": "",
    "MIXED": "x'; touch pwned; echo '$(id)",
}


class TestBaseEnvQuoting:
    def _script(self, env: dict[str, str]) -> str:
        return build_job_script(
            "~/work/x",
            "train1",
            ["python"],
            uv_path="~/.local/bin/uv",
            server_name="Newton",
            gpu_index=0,
            env=env,
            path_env={},
            results_dir="runs",
        )

    @pytest.mark.parametrize(("key", "value"), list(NASTY_VALUES.items()))
    def test_each_value_is_one_word(self, key: str, value: str) -> None:
        """SPEC_01「名前と値の検証」: 設定の値は引用して渡し，別のコマンドとして解釈されない."""
        env = build_job_env(0, [], git_commit="abc1234", base_env={key: value})
        assert _exports(self._script(env))[key] == value

    def test_all_values_together_survive_tmux_and_bash(self) -> None:
        """SPEC_01「名前と値の検証」: tmux → bash -c の 2 段を経ても値が 1 語のまま戻る."""
        env = build_job_env(0, ["CLI=$(id); x"], git_commit="abc1234", base_env=NASTY_VALUES)
        script = self._script(env)
        command = build_run_command("~/work/x", "train1", script, results_dir="runs")
        tokens = shlex.split(command)
        inner = shlex.split(tokens[tokens.index("new-session") + 6])
        assert inner[:2] == ["bash", "-c"]
        exports = _exports(inner[2])
        for key, value in NASTY_VALUES.items():
            assert exports[key] == value
        assert exports["CLI"] == "$(id); x"
        # 特殊文字が値の外に漏れて，余分なコマンドが増えていない
        assert "touch" not in shlex.split(inner[2])


# ---------------------------------------------------------------------------
# 結果の置き場（SPEC_02「`results`」の `dir`・SPEC_03「pull」「run」のログの置き場）
# ---------------------------------------------------------------------------


def _builders_with_results_dir(results_dir: str) -> dict[str, Callable[[], str]]:
    """結果の置き場を results_dir にして，その場所を使うコマンドを組み立てる関数を返す."""
    remote_dir = "~/work/proj"

    def job_script() -> str:
        return build_job_script(
            remote_dir,
            "train1",
            ["python", "-m", "train"],
            uv_path="~/.local/bin/uv",
            server_name="Newton",
            gpu_index=0,
            env=build_job_env(0, [], git_commit="abc1234"),
            path_env={},
            results_dir=results_dir,
        )

    return {
        "probe": lambda: build_probe_command(
            remote_dir, results_dir=results_dir, observe_sec=3, sample_interval_ms=500
        ),
        "job_script": job_script,
        # run には検証済みのスクリプトを渡す（結果の置き場は run の側でも確かめる）
        "run": lambda: build_run_command(remote_dir, "train1", "true", results_dir=results_dir),
        "log_exists": lambda: build_log_exists_command(
            remote_dir, "train1", results_dir=results_dir
        ),
        "logs": lambda: build_logs_command(
            remote_dir, "train1", results_dir=results_dir, lines=50, follow=False
        ),
        "kill": lambda: build_kill_command(remote_dir, "train1", results_dir=results_dir),
        "pull_list": lambda: build_pull_list_command(
            remote_dir, "20261119-120000_x_abc1234", results_dir=results_dir
        ),
        "pull_tar": lambda: build_pull_tar_command(remote_dir, results_dir=results_dir),
    }


def _commands_with_results_dir(results_dir: str) -> dict[str, str]:
    """結果の置き場を results_dir にして，その場所を使うコマンドを一通り組み立てる."""
    return {kind: build() for kind, build in _builders_with_results_dir(results_dir).items()}


# ログの場所を含むコマンドと，結果の置き場（の下の実験 ID）へ移動するコマンド
_LOG_KINDS = ["probe", "job_script", "run", "log_exists", "logs", "kill"]
_PULL_KINDS = ["pull_list", "pull_tar"]


class TestResultsDirInCommands:
    @pytest.mark.parametrize("kind", _LOG_KINDS + _PULL_KINDS)
    def test_changed_results_dir_leaves_no_runs(self, kind: str) -> None:
        """SPEC_02「`results`」: dir を変えると，サーバのコマンドに runs の決め打ちが残らない."""
        command = _commands_with_results_dir("zzout/store")[kind]
        assert "runs" not in command
        assert "zzout/store" in command

    @pytest.mark.parametrize("kind", _LOG_KINDS)
    def test_log_dir_is_under_results_dir(self, kind: str) -> None:
        """SPEC_03「run」: ログは <remote_dir>/<結果の置き場>/_remote_logs/ に置く."""
        command = _commands_with_results_dir("output/runs")[kind]
        assert "output/runs/_remote_logs" in command

    def test_job_log_path_follows_results_dir(self) -> None:
        """SPEC_02「`results`」: ジョブのログは <dir>/_remote_logs/<ジョブ名>.log."""
        assert (
            job_log_path("train1", results_dir="output/runs")
            == "output/runs/_remote_logs/train1.log"
        )

    def test_pull_commands_cd_into_results_dir(self) -> None:
        """SPEC_03「pull」: 対象はサーバの <remote_dir>/<結果の置き場>/<RUN_ID>/ の下."""
        commands = _commands_with_results_dir("output/runs")
        for kind in _PULL_KINDS:
            tokens = shlex.split(commands[kind])
            assert tokens[:2] == ["cd", "$HOME/work/proj/output/runs"], kind

    @pytest.mark.parametrize("results_dir", ["my res/out", "a;b $(id)", "x'y/`id`", "o|p&q"])
    def test_results_dir_is_one_word_in_pull_commands(self, results_dir: str) -> None:
        """SPEC_01「名前と値の検証」.

        結果の置き場は引用され，空白や特殊文字を含んでも 1 語で渡る.
        """
        commands = _commands_with_results_dir(results_dir)
        for kind in _PULL_KINDS:
            tokens = shlex.split(commands[kind])
            assert tokens[:2] == ["cd", f"$HOME/work/proj/{results_dir}"], kind

    @pytest.mark.parametrize("results_dir", ["my res/out", "a;b $(id)", "x'y/`id`"])
    def test_results_dir_is_one_word_in_log_commands(self, results_dir: str) -> None:
        """SPEC_01「名前と値の検証」: ログの場所も引用され，1 語のまま渡る."""
        commands = _commands_with_results_dir(results_dir)
        log = f"{results_dir}/_remote_logs/train1.log"
        run_tokens = shlex.split(commands["run"])
        mkdir = run_tokens.index("mkdir")
        assert run_tokens[mkdir : mkdir + 3] == ["mkdir", "-p", f"{results_dir}/_remote_logs"]
        assert log in shlex.split(commands["log_exists"])
        assert log in shlex.split(commands["logs"])
        assert log in shlex.split(commands["kill"])
        # ジョブのスクリプトは，ログの場所を 1 語の変数に入れてから使う
        # （shlex.split は区切りの ; を語に付けたまま返すため，末尾の ; を除いて比べる）
        script_tokens = [t.removesuffix(";") for t in shlex.split(commands["job_script"])]
        assert f"log={log}" in script_tokens
        probe_tokens = shlex.split(commands["probe"])
        assert any(
            t.startswith(f"$HOME/work/proj/{results_dir}/_remote_logs/") for t in probe_tokens
        )

    @pytest.mark.parametrize(
        "results_dir",
        ["", "~", "~/x", "/x", "../x", "a/../b", "a//b", "a/", "./a", "a\\b", "a\x00b"],
    )
    @pytest.mark.parametrize("kind", _LOG_KINDS + _PULL_KINDS)
    def test_results_dir_outside_remote_dir_is_rejected(self, results_dir: str, kind: str) -> None:
        """SPEC_01「安全の枠」.

        remote_dir の外を指す結果の置き場では，サーバのコマンドを組み立てない.
        """
        with pytest.raises(ValueError):
            _builders_with_results_dir(results_dir)[kind]()


# ---------------------------------------------------------------------------
# run.exclude_groups の組み立て（SPEC_02「`exclude_groups` の書き方」，SPEC_03「run」）
# ---------------------------------------------------------------------------


def _script_with_groups(
    groups: object, *, gpu_index: int | None = 0, command: list[str] | None = None
) -> str:
    return build_job_script(
        "~/work/TongueSegModel",
        "train1",
        command or ["tsm-train", "--config", "c.yaml"],
        uv_path="~/.local/bin/uv",
        server_name="Newton",
        gpu_index=gpu_index,
        env=build_job_env(gpu_index, [], git_commit="abc1234"),
        path_env={},
        results_dir="runs",
        exclude_groups=groups,  # type: ignore[arg-type]
    )


def _log_display_words(script: str) -> list[str]:
    """ジョブのログの開始行に出るコマンドの表示を，語に分けて返す（`uv` 以降）."""
    tokens = shlex.split(script)
    display = tokens[tokens.index("$(hostname)") + 1]
    words = shlex.split(display)
    return words[words.index("uv") :]


class TestExcludeGroupsInJobScript:
    @pytest.mark.parametrize(
        ("groups", "options"),
        [
            (["remote"], ["--no-group", "remote"]),
            (["remote", "dev.tools"], ["--no-group", "remote", "--no-group", "dev.tools"]),
            (["dev.tools", "remote"], ["--no-group", "dev.tools", "--no-group", "remote"]),
        ],
    )
    def test_no_group_options_come_right_after_uv_run_in_order(
        self, groups: list[str], options: list[str]
    ) -> None:
        """SPEC_02「`exclude_groups` の書き方」: uv run の直後・コマンドより前に書いた順で付く."""
        command = ["tsm-train", "--config", "c.yaml"]
        assert _uv_run_args(_script_with_groups(groups, command=command)) == [*options, *command]

    @pytest.mark.parametrize("groups", [(), []])
    def test_empty_list_adds_nothing(self, groups: object) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 空なら何も付かない（引数無しと同じ）."""
        assert _script_with_groups(groups) == _script(0, ["tsm-train", "--config", "c.yaml"])
        assert "--no-group" not in shlex.split(_script_with_groups(groups))

    def test_no_group_in_user_command_stays_in_command(self) -> None:
        """SPEC_02「`exclude_groups` の書き方」: コマンド本体の `--no-group` は本体の側に残る."""
        command = ["tsm-train", "--no-group", "x"]
        args = _uv_run_args(_script_with_groups(["remote"], command=command))
        assert args == ["--no-group", "remote", *command]

    @pytest.mark.parametrize("gpu_index", [0, None])
    def test_added_for_gpu_and_cpu_jobs(self, gpu_index: int | None) -> None:
        """SPEC_02「`exclude_groups` の書き方」: `--cpu` のジョブにも同じように付く."""
        args = _uv_run_args(_script_with_groups(["remote"], gpu_index=gpu_index))
        assert args[:2] == ["--no-group", "remote"]

    @pytest.mark.parametrize("groups", [["remote"], ["remote", "dev.tools"], []])
    def test_log_header_display_matches_actual_command(self, groups: list[str]) -> None:
        """SPEC_02「`exclude_groups` の書き方」: ログの開始行の表示も実際と同じ."""
        script = _script_with_groups(groups)
        assert _log_display_words(script) == ["uv", "run", *_uv_run_args(script)]

    @pytest.mark.parametrize("name", ["-x", "--frozen", "a b", "x;rm", "$(id)", "remote\n", "", 1])
    def test_invalid_name_is_rejected_by_builder(self, name: object) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 組み立ての側でも名前を確かめる."""
        with pytest.raises(ValueError):
            _script_with_groups(["remote", name])

    def test_single_string_instead_of_list_is_rejected(self) -> None:
        """SPEC_02「`run`」: 一覧の代わりに 1 つの文字列を渡すと組み立てない."""
        with pytest.raises(ValueError):
            _script_with_groups("remote")
