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

TIASJudgeModel の tests/remote/test_commands.py の移植．本リポジトリでの変更（接続先は
`host` と省略できる `user`・probe の `@@tsm-user`・`TIAS_DATA_ROOT` の削除・書式の検証は
`fullmatch`）と，シェルの特殊文字を含む引数の引用の確認を足した．

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

from __future__ import annotations

import shlex

import pytest

from tongue_seg_model.remote.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="192.168.23.14",
        user="hasegawa",
        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 "hasegawa@192.168.23.14" in argv
        assert argv[-1] == "echo hi"
        # 接続先より前にオプションがある
        assert j < argv.index("hasegawa@192.168.23.14")

    def test_without_jump_host(self) -> None:
        argv = _argv(None)
        assert "-J" not in argv
        assert "hasegawa@192.168.23.14" in argv

    @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_without_user_uses_host_only(self) -> None:
        # ~/.ssh/config の Host 名だけを渡す（アドレス・ユーザー名・鍵は手元の ssh の設定）
        argv = build_ssh_argv(
            "ssh",
            host="Newton",
            user=None,
            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",
            "user": None,
            "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",
            user="u",
            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", "user", "jump_host"])
    def test_rejects_option_like_or_unsafe_destination(self, bad: str, field: str) -> None:
        kwargs = {"host": "h", "user": "u", "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", "192.168.23.14", "user_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", 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", 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", 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", 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", 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", observe_sec=3, sample_interval_ms=500)
        assert "@@tias" not in command
        assert "@@tsm-" 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", 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:
    """`TSM_GIT_COMMIT`（SPEC_03「run」・SPEC_01「実験の出力」）."""

    def test_env_var_name(self) -> None:
        assert GIT_COMMIT_ENV_VAR == "TSM_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["TSM_GIT_COMMIT"] == "abc1234-dirty"

    def test_job_env_without_git_commit_does_not_set_it(self) -> None:
        env = build_job_env(0, [])
        assert "TSM_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, ["TSM_GIT_COMMIT=fake"], git_commit=git_commit)


class TestReservedEnv:
    @pytest.mark.parametrize(
        "key",
        [
            "CUDA_VISIBLE_DEVICES",
            "CUDA_DEVICE_ORDER",
            "PYTHONUNBUFFERED",
            "TSM_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 は外した（本リポジトリはバンドルだけを読む．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={},
    )


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["TSM_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 TSM_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 TSM_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={},
            )

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

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


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)
        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")
        # = を前置して完全一致（前方一致で別のジョブを選ばない）
        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")


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", lines=50, follow=False)
        assert "tail -n 50 runs/_remote_logs/train1.log" in command
        follow = build_logs_command("~/w", "train1", 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", lines=-1, follow=False)
        with pytest.raises(ValueError):
            build_logs_command("~/w", "a;b", 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)")
        assert "tmux kill-session -t =train1" in build_kill_command("~/w", "train1")
        assert job_log_path("train1") == "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")
        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")
        assert "tar --null --no-recursion -T - -cf -" in command
