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

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

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

from __future__ import annotations

from collections.abc import Sequence
from hashlib import sha256

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

from labremote.cleanup import (
    CleanJudgement,
    JobLogEntry,
    LocalFile,
    LsSummary,
    RemoteFile,
    RemoteListing,
    RunDirEntry,
    ServerLeftovers,
    classify_clean,
)
from labremote.commands import SSH_FAILURE_RC
from labremote.config import GpuFreeThreshold, ResultsConfig, 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_clean_report,
    format_forced_warning,
    format_ls_incomplete_warning,
    format_ls_report,
    format_ls_server,
    format_ls_unchecked_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")


# ---------------------------------------------------------------------------
# ls の表示（SPEC_03「ls」）
# ---------------------------------------------------------------------------

LS_RUN_A = "20261119-120000_demo_abc1234"
LS_RUN_B = "20261120-090000_demo_def5678"


def _listing(**kwargs: object) -> RemoteListing:
    base: dict[str, object] = {
        "remote_dir_exists": True,
        "total_bytes": 5 * 1024**3,
        "venv_bytes": 3 * 1024**3,
        "results_dir_exists": True,
        "logs_dir_exists": True,
        "run_dirs": (
            RunDirEntry(LS_RUN_A, 37, 120 * 1024**2, True),
            RunDirEntry(LS_RUN_B, 4, 2048, True),
        ),
        "job_logs": (JobLogEntry("train1", 2048, True), JobLogEntry("eval2", 10, False)),
        "other_in_results": 2,
        "other_in_logs": 1,
    }
    base.update(kwargs)
    return RemoteListing(**base)  # type: ignore[arg-type]


def _line_with(text: str, needle: str) -> str:
    (line,) = [line for line in text.splitlines() if needle in line]
    return line


class TestFormatLsServer:
    def test_shows_run_ids_counts_sizes_and_local(self) -> None:
        """SPEC_03「ls」: 実験 ID・件数・大きさ・手元にあるか."""
        text = format_ls_server(ServerLeftovers("Newton", _listing()), frozenset({LS_RUN_A}))
        assert "Newton" in text
        line_a = _line_with(text, LS_RUN_A)
        assert "37" in line_a
        assert format_size(120 * 1024**2) in line_a
        assert "手元: あり" in line_a
        line_b = _line_with(text, LS_RUN_B)
        assert "4" in line_b
        assert format_size(2048) in line_b
        assert "手元: なし" in line_b

    def test_shows_job_logs_running_and_stopped(self) -> None:
        """SPEC_03「ls」: ジョブのログの状態は「実行中」「停止中」."""
        text = format_ls_server(ServerLeftovers("Newton", _listing()), frozenset())
        line_t = _line_with(text, "train1")
        assert "実行中" in line_t and "停止中" not in line_t
        assert format_size(2048) in line_t
        line_e = _line_with(text, "eval2")
        assert "停止中" in line_e and "実行中" not in line_e

    def test_shows_remote_dir_and_venv_sizes_and_others(self) -> None:
        """SPEC_03「ls」: remote_dir 全体と .venv の大きさ，その他の件数."""
        text = format_ls_server(ServerLeftovers("Newton", _listing()), frozenset())
        assert format_size(5 * 1024**3) in text
        assert format_size(3 * 1024**3) in text
        assert ".venv" in text
        others = _line_with(text, "その他")
        assert "2" in others and "1" in others

    def test_states_are_distinguishable(self) -> None:
        """SPEC_03「ls」: remote_dir が無い・0 件・接続不可・確認できない，を区別できる."""
        texts = {
            "no_remote_dir": format_ls_server(
                ServerLeftovers("Newton", RemoteListing(remote_dir_exists=False)), frozenset()
            ),
            "zero": format_ls_server(
                ServerLeftovers(
                    "Newton",
                    _listing(run_dirs=(), job_logs=(), other_in_results=0, other_in_logs=0),
                ),
                frozenset(),
            ),
            "unreachable": format_ls_server(
                ServerLeftovers("Newton", None, "応答がタイムアウトした", unreachable=True),
                frozenset(),
            ),
            "unreadable": format_ls_server(
                ServerLeftovers("Newton", None, "出力を解釈できない"), frozenset()
            ),
        }
        assert len(set(texts.values())) == 4
        assert "接続不可" in texts["unreachable"]
        assert "応答がタイムアウトした" in texts["unreachable"]
        assert "確認できない" in texts["unreadable"]
        assert "接続不可" not in texts["unreadable"]
        assert "コードの置き場が無い" in texts["no_remote_dir"]
        assert "0 件" in texts["zero"]
        # 接続不可・確認できないを「何も残っていない」と表示しない
        for key in ("unreachable", "unreadable"):
            assert "何も残っていない" not in texts[key]
            assert "0 件" not in texts[key]
        for text in texts.values():
            assert "Newton" in text

    def test_missing_results_and_logs_dirs_are_zero(self) -> None:
        listing = RemoteListing(remote_dir_exists=True, total_bytes=1024)
        text = format_ls_server(ServerLeftovers("Newton", listing), frozenset())
        assert "実験フォルダ: 0 件" in text
        assert "ジョブのログ: 0 件" in text

    def test_incomplete_run_dir_has_note(self) -> None:
        """SPEC_03「ls」: 数え切れなかったときは，実際より少ない可能性があることを添える."""
        listing = _listing(
            run_dirs=(
                RunDirEntry(LS_RUN_A, 3, 4096, False),
                RunDirEntry(LS_RUN_B, 3, 4096, True),
            )
        )
        text = format_ls_server(ServerLeftovers("Newton", listing), frozenset())
        assert "少ない" in _line_with(text, LS_RUN_A)
        assert "少ない" not in _line_with(text, LS_RUN_B)

    def test_incomplete_sizes_have_note(self) -> None:
        listing = _listing(sizes_complete=False)
        text = format_ls_server(ServerLeftovers("Newton", listing), frozenset())
        assert "少ない" in _line_with(text, ".venv")

    def test_complete_listing_has_no_note(self) -> None:
        text = format_ls_server(ServerLeftovers("Newton", _listing()), frozenset())
        assert "少ない" not in text

    def test_report_joins_all_servers_in_order(self) -> None:
        results = [
            ServerLeftovers("Newton", _listing()),
            ServerLeftovers("Archimedes", None, "x", unreachable=True),
        ]
        text = format_ls_report(results, frozenset())
        assert text.endswith("\n")
        assert text.index("[Newton]") < text.index("[Archimedes]")


def _summary(**kwargs: object) -> LsSummary:
    base: dict[str, object] = {
        "unreachable": (),
        "unreadable": (),
        "incomplete": (),
        "all_unreachable": False,
    }
    base.update(kwargs)
    return LsSummary(**base)  # type: ignore[arg-type]


class TestLsWarnings:
    def test_no_warning_when_all_ok(self) -> None:
        assert format_ls_unchecked_warning(_summary()) is None
        assert format_ls_incomplete_warning(_summary()) is None

    def test_unchecked_warning_names_all_servers(self) -> None:
        """SPEC_03「ls」: 確かめられなかったサーバを最後に警告する（全部の名前を含む）."""
        text = format_ls_unchecked_warning(
            _summary(unreachable=("Newton", "Archimedes"), unreadable=("Curie",))
        )
        assert text is not None
        for name in ("Newton", "Archimedes", "Curie"):
            assert name in text
        assert "\n" not in text

    @pytest.mark.parametrize("field", ["unreachable", "unreadable"])
    def test_unchecked_warning_for_each_kind(self, field: str) -> None:
        text = format_ls_unchecked_warning(_summary(**{field: ("Newton",)}))
        assert text is not None and "Newton" in text

    def test_incomplete_does_not_make_unchecked_warning(self) -> None:
        assert format_ls_unchecked_warning(_summary(incomplete=("Newton",))) is None

    def test_incomplete_warning_names_all_servers(self) -> None:
        text = format_ls_incomplete_warning(_summary(incomplete=("Newton", "Archimedes")))
        assert text is not None
        assert "Newton" in text and "Archimedes" in text
        assert "\n" not in text

    def test_unreachable_does_not_make_incomplete_warning(self) -> None:
        assert format_ls_incomplete_warning(_summary(unreachable=("Newton",))) is None


# ---------------------------------------------------------------------------
# clean RUN_ID の表示（SPEC_03「clean」の「表示」）
# ---------------------------------------------------------------------------

CLEAN_RUN = "20261119-120000_demo_abc1234"
# 表示に出てはならない，サーバから来た名前の目印
_SECRET = "secretfile_w4"
_CLEAN_PROJECT_WORDS = [*_PROJECT_WORDS, "tsm", "tongueseg", "tias", "resunet"]


def _remote(path: str, data: bytes) -> RemoteFile:
    return RemoteFile(path, True, len(data), sha256(data).hexdigest())


def _local(data: bytes) -> LocalFile:
    return LocalFile(len(data), sha256(data).hexdigest())


def _judgement(
    *, unexplained: bool, checkpoints: bool = False, flag: bool = False
) -> CleanJudgement:
    files = [
        _remote(f"{_SECRET}_m.txt", b"a" * 1000),
        _remote(f"sub_{_SECRET}/x.txt", b"b" * 2000),
        _remote("cache.bin", b"c" * 3000),
    ]
    local = {files[0].rel_path: _local(b"a" * 1000), files[1].rel_path: _local(b"b" * 2000)}
    if checkpoints:
        files.append(_remote(f"checkpoints/{_SECRET}.pth", b"w" * 5000))
    if unexplained:
        files += [
            _remote(f"{_SECRET}_extra.txt", b"e" * 700),
            RemoteFile(f"{_SECRET}_link", False),
            _remote(f"{_SECRET}/../escape", b"u"),
        ]
    results = ResultsConfig.model_validate(
        {
            "checkpoints": {"dir": "checkpoints", "files": []},
            "discard": {"files": ["cache.bin"]},
        }
    )
    return classify_clean(files, local, results, discard_checkpoints=flag)


def _clean_report(judgement: CleanJudgement) -> str:
    return format_clean_report("Newton", CLEAN_RUN, judgement, checkpoints_dir="checkpoints")


class TestFormatCleanReport:
    def test_deletable_shows_counts_sizes_and_conclusion(self) -> None:
        judgement = _judgement(unexplained=False)
        out = _clean_report(judgement)
        assert "Newton" in out and CLEAN_RUN in out
        assert judgement.deletable
        lines = out.splitlines()
        (matched,) = [line for line in lines if line.strip().startswith("一致")]
        assert "2 件" in matched and format_size(3000) in matched
        (discard,) = [line for line in lines if line.strip().startswith("捨ててよい")]
        assert "1 件" in discard and format_size(3000) in discard
        (unexp,) = [line for line in lines if line.strip().startswith("説明がつかない")]
        assert "0 件" in unexp
        assert "消せる" in out and "消せない" not in out
        assert format_size(6000) in lines[0] and "3" in lines[0]

    def test_checkpoints_line_with_flag(self) -> None:
        judgement = _judgement(unexplained=False, checkpoints=True, flag=True)
        out = _clean_report(judgement)
        (weights,) = [line for line in out.splitlines() if line.strip().startswith("重み")]
        assert "1 件" in weights and format_size(5000) in weights
        assert "消せる" in out

    def test_not_deletable_shows_conclusion_and_next_steps(self) -> None:
        judgement = _judgement(unexplained=True)
        out = _clean_report(judgement)
        assert not judgement.deletable
        assert "消せない" in out
        assert f"{judgement.unexplained.count} 件" in out
        (unexp,) = [line for line in out.splitlines() if line.strip().startswith("説明がつかない")]
        assert f"{judgement.unexplained.count} 件" in unexp
        # 次に何をすればよいか（回収する・discard に書く・サーバで確かめる）
        assert f"labremote pull {CLEAN_RUN}" in out
        assert "results.discard" in out
        assert "結論: 消せる" not in out

    def test_unexplained_checkpoints_show_both_options(self) -> None:
        judgement = _judgement(unexplained=False, checkpoints=True, flag=False)
        out = _clean_report(judgement)
        assert not judgement.deletable
        assert "--with-checkpoints" in out
        assert "--discard-checkpoints" in out

    def test_no_checkpoint_hint_without_checkpoints(self) -> None:
        out = _clean_report(_judgement(unexplained=True))
        assert "--discard-checkpoints" not in out

    def test_empty_run_dir_is_deletable(self) -> None:
        judgement = classify_clean([], {}, ResultsConfig(), discard_checkpoints=False)
        out = _clean_report(judgement)
        assert "消せる" in out and "消せない" not in out

    @pytest.mark.parametrize(
        "kwargs",
        [
            {"unexplained": False},
            {"unexplained": True},
            {"unexplained": True, "checkpoints": True},
            {"unexplained": False, "checkpoints": True, "flag": True},
        ],
    )
    def test_no_file_names_and_no_project_words(self, kwargs: dict) -> None:
        """SPEC_03「clean」: 相対パス・ファイル名は表示に出さない．プロジェクトの言葉も出さない."""
        out = _clean_report(_judgement(**kwargs))
        assert _SECRET not in out
        assert "secretfile" not in out
        assert "escape" not in out and "cache.bin" not in out
        for word in _CLEAN_PROJECT_WORDS:
            assert word not in out.lower()

    def test_checkpoints_dir_from_config_is_shown(self) -> None:
        judgement = classify_clean(
            [_remote("weights/a", b"x")],
            {},
            ResultsConfig.model_validate({"checkpoints": {"dir": "weights", "files": []}}),
            discard_checkpoints=False,
        )
        out = format_clean_report("Newton", CLEAN_RUN, judgement, checkpoints_dir="weights")
        assert "weights/" in out
        assert "--discard-checkpoints" in out
