"""GPU 一覧の表示のテスト.

各 GPU の状態・使い方の型と使用率の平均／最大・計算プロセスごとの所有ユーザー（自分は「自分」）・
経過時間・SM 使用率の最大が表示されること．

設定にアドレス・ユーザー名を書くキーは無いため，見出しはサーバ名（ssh の Host 名）だけを出し，
「自分」は probe の `@@labremote-user` で決まる．
"""

from __future__ import annotations

from collections.abc import Sequence

import pytest
from probe_helpers import PMON_HEADER, gpu_line, probe_text, sample_lines

from labremote.commands import SSH_FAILURE_RC
from labremote.config import GpuFreeThreshold, ServerConfig
from labremote.gpu import GpuSelection, GpuState, ServerProbe, parse_probe_output, select_gpu
from labremote.report import (
    describe_skipped_links,
    describe_ssh_failure,
    describe_target,
    format_forced_warning,
    format_no_cpu_server_error,
    format_no_gpu_error,
    format_not_ready_alternative,
    format_project_line,
    format_pull_skipped,
    format_server_report,
    format_shared_warning,
    format_size,
    format_ssh_hint,
    last_stderr_line,
)

THRESHOLD = GpuFreeThreshold(
    max_memory_used_mib=1024, max_utilization_percent=80, observe_sec=10, sample_interval_ms=500
)
UUID0 = "GPU-0000"
SERVER = ServerConfig(
    name="Newton",
    priority=1,
    remote_dir="~/work/DemoProject",
    data_ready=True,
)


def _probe(remote_user: str | None = "carol", server: ServerConfig = SERVER) -> ServerProbe:
    text = probe_text(
        [gpu_line(0, UUID0, used=500, util=0)],
        # 平均 21%・最大 74%（断続的に使用）
        samples=sample_lines(0, [0, 74, 10, 0], memory=500),
        pmon=[
            *PMON_HEADER,
            "    0        100     C     74      1      -      -      -      -    python",
            "    0        200     C      5      1      -      -      -      -    python",
        ],
        apps=[f"{UUID0}, 100, 250", f"{UUID0}, 200, 250"],
        owners=["100 carol 99720", "200 dave 45"],
        remote_user=remote_user,
    )
    return ServerProbe(server, parse_probe_output(text, THRESHOLD))


def test_report_shows_state_pattern_users_elapsed_and_sm() -> None:
    report = format_server_report([_probe()], show_jobs=False)
    assert "Newton" in report
    assert "空き（利用者あり）" in report
    assert "断続的に使用" in report
    assert "平均 21%" in report
    assert "最大 74%" in report
    assert "自分" in report
    assert "dave" in report
    assert "27.7 時間" in report
    assert "SM 最大 74%" in report


def test_report_marks_unreachable_server() -> None:
    probe = ServerProbe(SERVER, None, "Connection timed out")
    report = format_server_report([probe], show_jobs=True)
    assert "Newton" in report
    assert "接続不可" in report


def test_shared_selection_warns_with_user_names() -> None:
    selection = select_gpu([_probe()])
    assert selection is not None
    warning = format_shared_warning(selection)
    assert warning is not None
    assert "dave" in warning


def test_report_without_own_user_does_not_mark_self() -> None:
    # 自分の名前が分からない（@@labremote-user が無い）ときは誰も「自分」にしない
    report = format_server_report([_probe(None)], show_jobs=False)
    assert "自分" not in report
    assert "carol" in report


def test_shared_warning_hides_own_user_name() -> None:
    selection = select_gpu([_probe()])
    assert selection is not None
    warning = format_shared_warning(selection)
    assert warning is not None
    assert "carol" not in warning


def test_report_header_shows_server_name_only() -> None:
    # 接続先はサーバ名と同じ．[user@]host の形は出さない
    report = format_server_report([_probe()], show_jobs=False)
    first = report.splitlines()[0]
    assert first.startswith("[Newton]  priority=1  ")
    assert "@" not in first
    assert "None" not in report


# ---------------------------------------------------------------------------
# 表示の言葉（SPEC_03「表示の言葉」「表示する項目」）
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("name", ["DemoProject", "demo-project_2", "日本語の名前"])
def test_project_line_shows_name_as_is_in_one_line(name: str) -> None:
    """SPEC_03「表示の言葉」: gpus・status の先頭に project.name を 1 行で出す."""
    line = format_project_line(name)
    assert name in line
    assert "\n" not in line
    assert "\r" not in line


def _probe_with_others(others: list[str], jobs: Sequence[str] = ()) -> ServerProbe:
    text = probe_text(
        [gpu_line(0, UUID0, used=5, util=0)],
        apps=[],
        jobs=list(jobs),
        others=others,
        remote_user="carol",
    )
    return ServerProbe(SERVER, parse_probe_output(text, THRESHOLD))


@pytest.mark.parametrize("others", [["hidden-session-a"], ["hidden-a", "hidden-b", "hidden-c"]])
def test_status_counts_other_sessions_without_names(others: list[str]) -> None:
    """SPEC_03「表示する項目」: ジョブでない tmux セッションは件数だけを出し，名前を出さない."""
    report = format_server_report([_probe_with_others(others, jobs=["train1"])], show_jobs=True)
    count_lines = [
        line for line in report.splitlines() if "このプロジェクトのジョブではない" in line
    ]
    assert len(count_lines) == 1
    assert str(len(others)) in count_lines[0]
    assert "件" in count_lines[0]
    for name in others:
        assert name not in report
    # 実行中のジョブの名前は出す
    assert "train1" in report
    # ツールを指す古い書き方は使わない（SPEC_03「表示の言葉」）
    assert "このツール" not in report


def test_status_without_other_sessions_has_no_count_line() -> None:
    """SPEC_03「表示する項目」: ジョブでないセッションが無ければ件数の行を出さない."""
    report = format_server_report([_probe_with_others([], jobs=["train1"])], show_jobs=True)
    assert "このプロジェクトのジョブではない" not in report
    assert "tmux セッション" not in report


def test_gpus_does_not_show_session_count_line() -> None:
    """SPEC_03「表示する項目」: 件数の行は status のもの（gpus はジョブを出さない）."""
    report = format_server_report([_probe_with_others(["hidden-a"])], show_jobs=False)
    assert "hidden-a" not in report
    assert "このプロジェクトのジョブではない" not in report


# ---------------------------------------------------------------------------
# CLI の表示・メッセージの組み立て
# ---------------------------------------------------------------------------

# どのプロジェクトのメッセージにも出さない言葉（SPEC_03「表示の言葉」）
_PROJECT_WORDS = ["バンドル", "学習データ", "このツール"]


class TestFormatSize:
    @pytest.mark.parametrize(
        ("num_bytes", "unit"),
        [
            (0, " B"),
            (1, " B"),
            (1023, " B"),
            (1024, " KB"),
            (1024 * 1024 - 1024, " KB"),
            (1024 * 1024, " MB"),
            (1024**3 - 1024 * 1024, " MB"),
            (1024**3, " GB"),
            (5 * 1024**4, " GB"),
        ],
    )
    def test_unit_changes_at_1024(self, num_bytes: int, unit: str) -> None:
        assert format_size(num_bytes).endswith(unit)
        if unit == " B":
            assert not format_size(num_bytes).endswith("KB")

    def test_values(self) -> None:
        assert format_size(1023).startswith("1023")
        assert format_size(1024).startswith("1.0")
        assert format_size(1536).startswith("1.5")
        assert format_size(1024 * 1024).startswith("1.0")
        assert format_size(1024**3).startswith("1.0")
        # GB より上の単位は無い
        assert format_size(2048 * 1024**3).startswith("2048.0")


class TestLastStderrLine:
    @pytest.mark.parametrize("stderr", [b"", b"\n", b"\n\n  \n\t\n", b"   "], ids=repr)
    def test_empty_or_blank_gives_empty(self, stderr: bytes) -> None:
        assert last_stderr_line(stderr) == ""

    def test_last_non_empty_line_is_returned_stripped(self) -> None:
        stderr = b"first line\r\n  second line  \r\n\r\n   \n"
        assert last_stderr_line(stderr) == "second line"

    def test_long_line_is_cut(self) -> None:
        line = last_stderr_line(b"x" * 1000)
        assert 0 < len(line) < 1000
        assert set(line) == {"x"}

    def test_short_line_is_not_cut(self) -> None:
        assert last_stderr_line(b"y" * 100) == "y" * 100

    @pytest.mark.parametrize(
        "stderr", [b"\xff\xfe\x80 bad", b"ok\n\xe3\x81", b"\x00\xff"], ids=repr
    )
    def test_invalid_utf8_does_not_raise(self, stderr: bytes) -> None:
        assert isinstance(last_stderr_line(stderr), str)

    def test_utf8_is_decoded(self) -> None:
        assert last_stderr_line("接続できない\n".encode()) == "接続できない"


class TestDescribeSshFailure:
    def test_timeout(self) -> None:
        text = describe_ssh_failure(SSH_FAILURE_RC, b"Connection refused", timed_out=True)
        assert "タイムアウト" in text
        assert "Connection refused" not in text

    def test_ssh_failure_adds_last_stderr_line(self) -> None:
        text = describe_ssh_failure(SSH_FAILURE_RC, b"debug\nConnection refused\n", timed_out=False)
        assert str(SSH_FAILURE_RC) in text
        assert "Connection refused" in text
        assert "debug" not in text

    def test_ssh_failure_without_stderr(self) -> None:
        text = describe_ssh_failure(SSH_FAILURE_RC, b"", timed_out=False)
        assert str(SSH_FAILURE_RC) in text

    @pytest.mark.parametrize("rc", [1, 2, 90, 92, 127])
    def test_other_rc_does_not_add_stderr(self, rc: int) -> None:
        """リモートのコマンドの標準エラーはファイル名を含みうるため出さない."""
        text = describe_ssh_failure(rc, b"secret_file_name.png: error", timed_out=False)
        assert str(rc) in text
        assert "secret_file_name" not in text


class TestFormatSshHint:
    _STDERR = b"Host key verification failed.\r\n"

    def test_host_key_failure_gives_hint_with_host(self) -> None:
        hint = format_ssh_hint(SSH_FAILURE_RC, self._STDERR, host="Newton", jump_host=None)
        assert hint
        assert "ssh Newton" in hint
        assert "-J" not in hint

    def test_hint_with_jump_host(self) -> None:
        hint = format_ssh_hint(SSH_FAILURE_RC, self._STDERR, host="Newton", jump_host="labpc")
        assert "-J labpc" in hint
        assert "Newton" in hint
        assert hint.index("labpc") < hint.index("Newton")

    @pytest.mark.parametrize(
        ("rc", "stderr"),
        [
            (SSH_FAILURE_RC, b"Connection refused"),
            (SSH_FAILURE_RC, b""),
            (1, b"Host key verification failed."),
            (0, b"Host key verification failed."),
        ],
        ids=repr,
    )
    def test_no_hint_otherwise(self, rc: int, stderr: bytes) -> None:
        assert format_ssh_hint(rc, stderr, host="Newton", jump_host="labpc") == ""


class TestDescribeSkippedLinks:
    def test_zero_links(self) -> None:
        text = describe_skipped_links([])
        assert "0 件" in text
        assert "（" not in text

    def test_links_are_counted_and_named_in_order(self) -> None:
        text = describe_skipped_links(["a/link1", "b/link2", "link3"])
        assert "3 件" in text
        assert text.index("a/link1") < text.index("b/link2") < text.index("link3")
        assert "\n" not in text


class TestDescribeTarget:
    def test_gpu_with_state(self) -> None:
        text = describe_target("Newton", 1, "未使用")
        assert "Newton" in text
        assert "GPU 1" in text
        assert "未使用" in text

    def test_gpu_without_state(self) -> None:
        text = describe_target("Newton", 0)
        assert "GPU 0" in text
        assert "（" not in text

    def test_cpu_only(self) -> None:
        text = describe_target("Newton", None)
        assert "Newton" in text
        assert "CPU" in text
        assert "GPU 0" not in text


def _selection(state: GpuState, *, forced: bool = False, gpu_index: int = 2) -> GpuSelection:
    return GpuSelection(server=SERVER, gpu_index=gpu_index, state=state, forced=forced)


class TestRunMessages:
    @pytest.mark.parametrize("server_name", [None, "Newton"])
    def test_no_gpu_error_mentions_no_data(self, server_name: str | None) -> None:
        text = format_no_gpu_error(server_name, include_not_ready=True)
        assert "--no-data" in text
        assert "data_ready" not in text
        if server_name:
            assert server_name in text

    @pytest.mark.parametrize("server_name", [None, "Newton"])
    def test_no_gpu_error_mentions_data_ready(self, server_name: str | None) -> None:
        text = format_no_gpu_error(server_name, include_not_ready=False)
        assert "data_ready" in text
        assert "--no-data" not in text

    def test_no_gpu_error_wording_differs_by_no_data(self) -> None:
        assert format_no_gpu_error(None, include_not_ready=True) != format_no_gpu_error(
            None, include_not_ready=False
        )

    def test_no_cpu_server_error(self) -> None:
        with_data = format_no_cpu_server_error(include_not_ready=False)
        without = format_no_cpu_server_error(include_not_ready=True)
        assert "data_ready" in with_data
        assert "data_ready" not in without
        assert with_data != without

    @pytest.mark.parametrize("state", [GpuState.BUSY, GpuState.UNKNOWN])
    def test_forced_warning(self, state: GpuState) -> None:
        text = format_forced_warning(_selection(state, forced=True))
        assert "Newton" in text
        assert "GPU 2" in text
        assert str(state) in text
        assert "--force" in text

    def test_not_ready_alternative(self) -> None:
        text = format_not_ready_alternative(_selection(GpuState.UNUSED, gpu_index=3))
        assert "Newton" in text
        assert "GPU 3" in text
        assert "data_ready: false" in text
        assert "--no-data" in text
        assert "\n" not in text

    def test_messages_do_not_use_project_words(self) -> None:
        texts = [
            format_no_gpu_error(None, include_not_ready=False),
            format_no_gpu_error(None, include_not_ready=True),
            format_no_cpu_server_error(include_not_ready=False),
            format_no_cpu_server_error(include_not_ready=True),
            format_forced_warning(_selection(GpuState.BUSY, forced=True)),
            format_not_ready_alternative(_selection(GpuState.UNUSED)),
        ]
        for text in texts:
            for word in _PROJECT_WORDS:
                assert word not in text


class TestFormatPullSkipped:
    def test_without_checkpoints_has_no_note(self) -> None:
        text = format_pull_skipped(5, 0, "checkpoints")
        assert "5 件" in text
        assert "--with-checkpoints" not in text
        assert "checkpoints" not in text

    def test_with_checkpoints_has_note(self) -> None:
        text = format_pull_skipped(5, 2, "weights")
        assert "5 件" in text
        assert "2 件" in text
        assert "weights/" in text
        assert "--with-checkpoints" in text
        assert "\n" not in text

    def test_zero_skipped(self) -> None:
        assert "0 件" in format_pull_skipped(0, 0, "checkpoints")
