"""`ls` のサーバの出力の解析のテスト（SPEC_03「ls」）.

- 正常な出力から，実験フォルダ・ジョブのログ・その他の件数・大きさ・実行中かが読めること
- 解釈できない出力（空・目印が無い・途中で切れている・順が違う・数が読めない・知らない状態）を
  「何も残っていない」とせず `ValueError` にすること．メッセージにサーバから来た名前を入れないこと
- 実験 ID・ジョブ名の規則に合わない名前を表示に出さず「その他」に数えること
- `du`・`find` が失敗した記録を「数え切れなかった」とすること

サーバの出力はテストの中で組み立てる（`tests/ls_helpers.py`）．実サーバには接続しない．
"""

from __future__ import annotations

import pytest
from ls_helpers import (
    dir_record,
    encode_records,
    job_record,
    log_record,
    ls_missing_remote_dir,
    ls_output,
    ls_records,
)

from labremote.cleanup import (
    JobLogEntry,
    LsSummary,
    RemoteListing,
    RunDirEntry,
    ServerLeftovers,
    listed_run_ids,
    parse_ls_output,
    summarize_ls,
)
from labremote.commands import (
    LS_BEGIN_MARKER,
    LS_END_MARKER,
    LS_LOGS_END_MARKER,
    LS_LOGS_PREFIX,
    LS_REMOTE_DIR_PREFIX,
    LS_RESULTS_END_MARKER,
    LS_RESULTS_PREFIX,
    LS_SIZE_PREFIX,
    LS_TMUX_RC_PREFIX,
    LS_VENV_PREFIX,
)

RUN_A = "20261119-120000_demo_abc1234"
RUN_B = "20261120-090000_demo_def5678"
KIB = 1024

# 正常な出力（実験フォルダ 2 件・その他 1 件，ログ 2 件・その他 1 件，ジョブ 1 件と，
# ログの無いセッション 1 件）
NORMAL_RECORDS = ls_records(
    total_kib=1000,
    venv_kib=600,
    results=[dir_record(RUN_A, 3, 8), "other", dir_record(RUN_B, 0, 4)],
    logs=[log_record("train1.log", 123), log_record("old.log", 50), "other"],
    jobs=[job_record("train1"), job_record("manual")],
)
NORMAL = encode_records(NORMAL_RECORDS)


def _replace(records: list, index: int, new: object) -> list:
    out = list(records)
    out[index] = new
    return out


def _index(records: list, prefix: str) -> int:
    return next(i for i, r in enumerate(records) if isinstance(r, str) and r.startswith(prefix))


# ---------------------------------------------------------------------------
# 正常な出力
# ---------------------------------------------------------------------------


class TestParseNormal:
    def test_reads_run_dirs_logs_others_and_sizes(self) -> None:
        """SPEC_03「ls」: 実験フォルダ・ログ・その他・大きさ・実行中かを読む."""
        listing = parse_ls_output(NORMAL)
        assert listing.remote_dir_exists
        assert listing.total_bytes == 1000 * KIB
        assert listing.venv_bytes == 600 * KIB
        assert listing.sizes_complete
        assert listing.results_dir_exists and listing.logs_dir_exists
        assert listing.run_dirs == (
            RunDirEntry(RUN_A, 3, 8 * KIB, True),
            RunDirEntry(RUN_B, 0, 4 * KIB, True),
        )
        assert listing.other_in_results == 1
        assert listing.job_logs == (
            JobLogEntry("train1", 123, True),
            JobLogEntry("old", 50, False),
        )
        assert listing.other_in_logs == 1
        assert listing.complete

    def test_session_without_log_is_not_shown(self) -> None:
        """SPEC_03「ls」: ログの無いセッション（manual）は，表示に出ない."""
        listing = parse_ls_output(NORMAL)
        assert "manual" not in {log.name for log in listing.job_logs}
        assert "manual" not in {d.run_id for d in listing.run_dirs}

    def test_only_logs_with_job_are_running(self) -> None:
        """SPEC_03「ls」: 同じ名前の tmux のセッションがあるログだけが実行中."""
        data = ls_output(
            logs=[log_record("a1.log"), log_record("b2.log"), log_record("c3.log")],
            jobs=[job_record("b2"), job_record("zz")],
        )
        running = {log.name: log.running for log in parse_ls_output(data).job_logs}
        assert running == {"a1": False, "b2": True, "c3": False}

    def test_missing_remote_dir_means_nothing_left(self) -> None:
        """SPEC_03「ls」: remote_dir が無いときは「何も残っていない」."""
        listing = parse_ls_output(ls_missing_remote_dir())
        assert listing == RemoteListing(remote_dir_exists=False)
        assert listing.run_dirs == () and listing.job_logs == ()

    def test_missing_results_and_logs_dirs_are_zero(self) -> None:
        """SPEC_03「ls」: 結果の置き場・ログの置き場が無いときは 0 件."""
        listing = parse_ls_output(ls_output(results=None, logs=None, jobs=[job_record("x1")]))
        assert listing.remote_dir_exists
        assert not listing.results_dir_exists
        assert not listing.logs_dir_exists
        assert listing.run_dirs == () and listing.job_logs == ()
        assert listing.other_in_results == 0 and listing.other_in_logs == 0

    def test_empty_results_and_logs(self) -> None:
        listing = parse_ls_output(ls_output(results=[], logs=[]))
        assert listing.results_dir_exists and listing.logs_dir_exists
        assert listing.run_dirs == () and listing.job_logs == ()

    @pytest.mark.parametrize("tmux_rc", [1, 127])
    def test_tmux_failure_makes_all_logs_stopped(self, tmux_rc: int) -> None:
        """tmux が無い・動いていないときは，全部が停止中（エラーにしない）."""
        data = ls_output(logs=[log_record("train1.log")], tmux_rc=tmux_rc)
        listing = parse_ls_output(data)
        assert listing.job_logs == (JobLogEntry("train1", 10, False),)

    def test_zero_sized_run_dir_and_log(self) -> None:
        data = ls_output(results=[dir_record(RUN_A, 0, 0)], logs=[log_record("t1.log", 0)])
        listing = parse_ls_output(data)
        assert listing.run_dirs == (RunDirEntry(RUN_A, 0, 0, True),)
        assert listing.job_logs == (JobLogEntry("t1", 0, False),)

    def test_names_with_spaces_inside_record_do_not_shift_numbers(self) -> None:
        """名前は記録の最後の項目なので，名前の空白で数の位置がずれない（その他になる）."""
        data = ls_output(results=[dir_record("a 1 2 3 4", 7, 9)])
        listing = parse_ls_output(data)
        assert listing.run_dirs == ()
        assert listing.other_in_results == 1


# ---------------------------------------------------------------------------
# 数え切れなかった記録
# ---------------------------------------------------------------------------


class TestIncomplete:
    @pytest.mark.parametrize(("find_rc", "du_rc"), [(1, 0), (0, 1), (1, 1), (2, 0)])
    def test_failed_find_or_du_marks_run_dir_incomplete(self, find_rc: int, du_rc: int) -> None:
        """SPEC_03「ls」: find・du が失敗した実験フォルダは，数え切れなかった."""
        data = ls_output(results=[dir_record(RUN_A, 2, 8, find_rc=find_rc, du_rc=du_rc)])
        listing = parse_ls_output(data)
        assert listing.run_dirs == (RunDirEntry(RUN_A, 2, 8 * KIB, False),)
        assert not listing.complete

    @pytest.mark.parametrize(("total_rc", "venv_rc"), [(1, 0), (0, 1)])
    def test_failed_du_of_remote_dir_or_venv_is_incomplete(
        self, total_rc: int, venv_rc: int
    ) -> None:
        listing = parse_ls_output(ls_output(total_rc=total_rc, venv_rc=venv_rc))
        assert not listing.sizes_complete
        assert not listing.complete

    def test_incomplete_name_that_is_not_run_id_is_other(self) -> None:
        data = ls_output(results=[dir_record("bad name", 2, 8, find_rc=1)])
        listing = parse_ls_output(data)
        assert listing.run_dirs == ()
        assert listing.other_in_results == 1


# ---------------------------------------------------------------------------
# 解釈できない出力は「何も残っていない」にしない
# ---------------------------------------------------------------------------

_SECRET = "secretname_q7"

BROKEN_OUTPUTS: dict[str, bytes] = {
    "empty": b"",
    "only_nul": b"\0",
    "garbage": b"Welcome to the server\nLast login: yesterday\n",
    "no_begin": encode_records(NORMAL_RECORDS[1:]),
    "no_end": encode_records(NORMAL_RECORDS[:-1]),
    "missing_remote_dir_without_end": encode_records(
        [LS_BEGIN_MARKER, LS_REMOTE_DIR_PREFIX + "missing"]
    ),
    "missing_remote_dir_then_records": encode_records(
        [LS_BEGIN_MARKER, LS_REMOTE_DIR_PREFIX + "missing", f"{LS_SIZE_PREFIX}0 1", LS_END_MARKER]
    ),
    "no_results_end": encode_records([r for r in NORMAL_RECORDS if r != LS_RESULTS_END_MARKER]),
    "no_logs_end": encode_records([r for r in NORMAL_RECORDS if r != LS_LOGS_END_MARKER]),
    "no_tmux_rc": encode_records(
        [r for r in NORMAL_RECORDS if not (isinstance(r, str) and r.startswith(LS_TMUX_RC_PREFIX))]
    ),
    "no_size": encode_records(
        [r for r in NORMAL_RECORDS if not (isinstance(r, str) and r.startswith(LS_SIZE_PREFIX))]
    ),
    "no_venv": encode_records(
        [r for r in NORMAL_RECORDS if not (isinstance(r, str) and r.startswith(LS_VENV_PREFIX))]
    ),
    "size_and_venv_swapped": encode_records(
        [
            NORMAL_RECORDS[0],
            NORMAL_RECORDS[1],
            NORMAL_RECORDS[3],
            NORMAL_RECORDS[2],
            *NORMAL_RECORDS[4:],
        ]
    ),
    "logs_before_results": encode_records(
        [
            *ls_records()[:4],
            LS_LOGS_PREFIX + "missing",
            LS_RESULTS_PREFIX + "missing",
            f"{LS_TMUX_RC_PREFIX}0",
            LS_END_MARKER,
        ]
    ),
    "end_before_tmux": encode_records(
        [*ls_records()[:-2], LS_END_MARKER, f"{LS_TMUX_RC_PREFIX}0", LS_END_MARKER]
    ),
    "dir_record_in_logs": ls_output(logs=[dir_record(RUN_A)]),
    "log_record_in_results": ls_output(results=[log_record("t1.log")]),
    "other_in_jobs": ls_output(jobs=["other"]),
    "dir_record_in_jobs": ls_output(jobs=[dir_record(RUN_A)]),
    "unknown_record_in_results": ls_output(results=["file 1 x"]),
    "unknown_record_in_logs": ls_output(logs=["dir 1 x"]),
    "unknown_record_in_jobs": ls_output(jobs=["session x"]),
    # 数が数字でない・負・空・符号付き・小数・全角
    "dir_count_word": ls_output(results=[b"dir 0 0 many 4 " + RUN_A.encode()]),
    "dir_count_negative": ls_output(results=[b"dir 0 0 -1 4 " + RUN_A.encode()]),
    "dir_count_empty": ls_output(results=[b"dir 0 0  4 " + RUN_A.encode()]),
    "dir_count_plus": ls_output(results=[b"dir 0 0 +1 4 " + RUN_A.encode()]),
    "dir_kib_decimal": ls_output(results=[b"dir 0 0 1 1.5 " + RUN_A.encode()]),
    "dir_kib_fullwidth": ls_output(results=["dir 0 0 1 ４ " + RUN_A]),
    "dir_find_rc_word": ls_output(results=[b"dir x 0 1 4 " + RUN_A.encode()]),
    "dir_du_rc_negative": ls_output(results=[b"dir 0 -1 1 4 " + RUN_A.encode()]),
    "dir_too_few_fields": ls_output(results=[b"dir 0 0 1 4"]),
    "dir_too_few_fields2": ls_output(results=[b"dir 0 0 1"]),
    "dir_no_fields": ls_output(results=[b"dir "]),
    "size_negative": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX}0 -5")),
    "size_empty": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX}0 ")),
    "size_one_field": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX}0")),
    "size_word": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX}0 big")),
    "size_exponent": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX}0 1e3")),
    "size_rc_empty": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX} 5")),
    "venv_word": encode_records(_replace(NORMAL_RECORDS, 3, f"{LS_VENV_PREFIX}0 x")),
    "log_size_word": ls_output(logs=[b"log big train1.log"]),
    "log_size_negative": ls_output(logs=[b"log -3 train1.log"]),
    "log_size_empty": ls_output(logs=[b"log  train1.log"]),
    "log_no_name": ls_output(logs=[b"log 12"]),
    "tmux_rc_word": ls_output(tmux_rc=0).replace(
        f"{LS_TMUX_RC_PREFIX}0".encode(), f"{LS_TMUX_RC_PREFIX}x".encode()
    ),
    "tmux_rc_empty": ls_output(tmux_rc=0).replace(
        f"{LS_TMUX_RC_PREFIX}0".encode(), LS_TMUX_RC_PREFIX.encode()
    ),
    # 知らない状態
    "remote_state_unknown": encode_records(
        _replace(NORMAL_RECORDS, 1, LS_REMOTE_DIR_PREFIX + "exists")
    ),
    "remote_state_upper": encode_records(
        _replace(NORMAL_RECORDS, 1, LS_REMOTE_DIR_PREFIX + "PRESENT")
    ),
    "remote_state_trailing_space": encode_records(
        _replace(NORMAL_RECORDS, 1, LS_REMOTE_DIR_PREFIX + "present ")
    ),
    "remote_state_empty": encode_records(_replace(NORMAL_RECORDS, 1, LS_REMOTE_DIR_PREFIX)),
    "results_state_unknown": encode_records(
        _replace(NORMAL_RECORDS, _index(NORMAL_RECORDS, LS_RESULTS_PREFIX), "x")
    ),
    "results_state_bogus": encode_records(
        _replace(
            NORMAL_RECORDS, _index(NORMAL_RECORDS, LS_RESULTS_PREFIX), LS_RESULTS_PREFIX + "ok"
        )
    ),
    "logs_state_bogus": encode_records(
        _replace(NORMAL_RECORDS, _index(NORMAL_RECORDS, LS_LOGS_PREFIX), LS_LOGS_PREFIX + "ok")
    ),
    # 置き場が在るのに入れない（SPEC_03「ls」: 0 件とせず確認できない）
    "remote_unreadable": encode_records(
        [LS_BEGIN_MARKER, LS_REMOTE_DIR_PREFIX + "unreadable", LS_END_MARKER]
    ),
    "results_unreadable": encode_records(
        [
            *ls_records()[:4],
            LS_RESULTS_PREFIX + "unreadable",
            LS_LOGS_PREFIX + "missing",
            f"{LS_TMUX_RC_PREFIX}0",
            LS_END_MARKER,
        ]
    ),
    "logs_unreadable": encode_records(
        [
            *ls_records()[:4],
            LS_RESULTS_PREFIX + "missing",
            LS_LOGS_PREFIX + "unreadable",
            f"{LS_TMUX_RC_PREFIX}0",
            LS_END_MARKER,
        ]
    ),
    # 記録の区切りが NUL でない（改行区切りの出力）
    "newline_separated": b"\n".join(
        r if isinstance(r, bytes) else r.encode() for r in NORMAL_RECORDS
    ),
}


class TestParseBroken:
    @pytest.mark.parametrize("case", sorted(BROKEN_OUTPUTS))
    def test_unparsable_output_is_value_error(self, case: str) -> None:
        """SPEC_03「ls」: 解釈できない出力は「何も残っていない」にせず，ValueError にする."""
        with pytest.raises(ValueError):
            parse_ls_output(BROKEN_OUTPUTS[case])

    @pytest.mark.parametrize("cut", range(len(NORMAL) - 1))
    def test_truncated_output_is_value_error(self, cut: int) -> None:
        """SPEC_03「ls」: 途中で切れた出力（正常な出力を各位置で切ったもの）は ValueError.

        最後の NUL だけを落としたもの（終端の目印まで届いている）は，切れていない扱いでよい．
        """
        with pytest.raises(ValueError):
            parse_ls_output(NORMAL[:cut])

    @pytest.mark.parametrize("cut", range(len(ls_missing_remote_dir()) - 1))
    def test_truncated_missing_remote_dir_output_is_value_error(self, cut: int) -> None:
        """「コードの置き場が無い」の出力も，途中で切れていれば「何も残っていない」にしない."""
        with pytest.raises(ValueError):
            parse_ls_output(ls_missing_remote_dir()[:cut])

    def test_output_without_last_nul_is_still_complete(self) -> None:
        assert parse_ls_output(NORMAL[:-1]) == parse_ls_output(NORMAL)

    @pytest.mark.parametrize(
        "records",
        [
            [dir_record(_SECRET + " x")],
            [b"dir 0 0 many 4 " + _SECRET.encode()],
            [b"dir 0 0 1 " + _SECRET.encode()],
            [_SECRET],
            [log_record(_SECRET + ".log")],
        ],
        ids=["bad_dir_name_then_ok", "bad_count", "few_fields", "bare_name", "log_in_results"],
    )
    def test_error_message_does_not_contain_server_names(self, records: list) -> None:
        """SPEC_03「ls」・coding-style: エラーのメッセージにサーバから来た名前を入れない."""
        broken = ls_records(results=records, logs=[b"log x " + _SECRET.encode() + b".log"])
        with pytest.raises(ValueError) as excinfo:
            parse_ls_output(encode_records(broken))
        assert _SECRET not in str(excinfo.value)

    @pytest.mark.parametrize(
        "records",
        [
            {"jobs": [_SECRET]},
            {"logs": [b"log nan " + _SECRET.encode() + b".log"]},
            {"logs": [b"log 12"], "jobs": [job_record(_SECRET)]},
        ],
        ids=["bare_job", "bad_log_size", "log_without_name"],
    )
    def test_error_message_does_not_contain_server_names_in_logs(self, records: dict) -> None:
        with pytest.raises(ValueError) as excinfo:
            parse_ls_output(ls_output(**records))
        assert _SECRET not in str(excinfo.value)


# ---------------------------------------------------------------------------
# ログインの挨拶（始まりの目印より前・終わりの目印より後）
# ---------------------------------------------------------------------------


class TestSurroundingGarbage:
    @pytest.mark.parametrize(
        "banner",
        [
            b"Welcome\nLast login: Mon\n",
            b"motd\0with\0nuls\0",
            b"\x1b[31mcolor\x1b[0m\n",
            b"\xff\xfe broken utf-8\n",
        ],
    )
    def test_banner_before_begin_is_ignored(self, banner: bytes) -> None:
        assert parse_ls_output(banner + NORMAL) == parse_ls_output(NORMAL)

    @pytest.mark.parametrize("trailer", [b"bye\n", b"\0garbage\0", b"\xff\0"])
    def test_garbage_after_end_is_ignored(self, trailer: bytes) -> None:
        assert parse_ls_output(NORMAL + trailer) == parse_ls_output(NORMAL)

    # 目印が 2 つ以上ある出力は，どれが本物かを決められないので拒否する（SPEC_03「ls」の「安全」）．
    # 挨拶に紛れた偽の一覧（何も残っていない）を本物として読むと，「使い終えた」と見誤る
    @pytest.mark.parametrize(
        "fake",
        [
            ls_missing_remote_dir(),
            ls_output(results=[], logs=[]),
            ls_output(results=None, logs=None),
        ],
        ids=["remote_dir_missing", "empty_dirs", "no_dirs"],
    )
    def test_fake_listing_before_real_one_is_rejected(self, fake: bytes) -> None:
        with pytest.raises(ValueError, match="解釈できない"):
            parse_ls_output(fake + NORMAL)

    def test_fake_full_listing_after_end_is_rejected(self) -> None:
        with pytest.raises(ValueError, match="解釈できない"):
            parse_ls_output(NORMAL + ls_missing_remote_dir())

    @pytest.mark.parametrize("marker", [LS_BEGIN_MARKER, LS_END_MARKER])
    @pytest.mark.parametrize("position", ["before", "after"])
    def test_duplicated_marker_is_rejected(self, marker: str, position: str) -> None:
        extra = b"\0" + marker.encode() + b"\0"
        data = extra + NORMAL if position == "before" else NORMAL + extra
        with pytest.raises(ValueError, match="解釈できない"):
            parse_ls_output(data)

    def test_marker_inside_a_name_record_is_not_a_marker(self) -> None:
        """名前が目印と同じ文字列でも，記録の全体が目印に一致しなければ目印として数えない."""
        banner = f"dir 0 0 1 4 {LS_BEGIN_MARKER}".encode() + b"\0"
        assert parse_ls_output(banner + NORMAL) == parse_ls_output(NORMAL)


# ---------------------------------------------------------------------------
# 名前の検証（規則に合わない名前は表示せず「その他」に数える）
# ---------------------------------------------------------------------------

BAD_RUN_IDS: list[str | bytes] = [
    "",
    "a b",
    " lead",
    "trail ",
    "a..b",
    "..",
    ".",
    "abc.",
    "run.",
    ".hidden",
    "_under",
    "-dash",
    "--help",
    "nul",
    "NUL",
    "con",
    "CON.txt",
    "com1",
    "lpt9.log",
    "aux",
    "a;b",
    "$(id)",
    "a$(id)",
    "a`id`",
    "a|b",
    "a&b",
    "a>b",
    "a*b",
    "a?b",
    "a'b",
    'a"b',
    "a/b",
    "a\\b",
    "a:b",
    "a\x1b[31mred",
    "a\x07bell",
    "a\x7fdel",
    "a\nb",
    "a\rb",
    "a\tb",
    "abc\n",
    "日本語",
    "a​b",
    b"a\xffb",
    b"\xc3\x28",
    "a" * 201,
]

BAD_JOB_NAMES: list[str | bytes] = [
    "",
    "a b",
    "-x",
    "_x",
    ".x",
    "a.b",
    "a..b",
    "a;b",
    "$(id)",
    "a`b`",
    "a/b",
    "a\x1b[0m",
    "a\nb",
    "train1\n",
    "日本語",
    b"a\xffb",
    "a" * 65,
]


class TestNameValidation:
    @pytest.mark.parametrize("name", BAD_RUN_IDS, ids=repr)
    def test_bad_run_id_is_counted_as_other(self, name: str | bytes) -> None:
        """SPEC_03「ls」: 実験 ID の規則に合わない名前は，実験フォルダとして出ず「その他」."""
        data = ls_output(results=[dir_record(name, 5, 9), dir_record(RUN_A, 1, 1)])
        listing = parse_ls_output(data)
        assert [d.run_id for d in listing.run_dirs] == [RUN_A]
        assert listing.other_in_results == 1
        assert listed_run_ids([ServerLeftovers("Newton", listing)]) == frozenset({RUN_A})

    @pytest.mark.parametrize("name", ["a", "A1", "x" * 200, "1.2.3", "a_b-c.d", RUN_A])
    def test_good_run_id_is_listed(self, name: str) -> None:
        listing = parse_ls_output(ls_output(results=[dir_record(name, 1, 1)]))
        assert [d.run_id for d in listing.run_dirs] == [name]
        assert listing.other_in_results == 0

    @pytest.mark.parametrize("name", BAD_JOB_NAMES, ids=repr)
    def test_bad_job_log_name_is_counted_as_other(self, name: str | bytes) -> None:
        """SPEC_03「ls」: `.log` を外した名前がジョブ名の規則に合わないものは「その他」."""
        file_name = name + (b".log" if isinstance(name, bytes) else ".log")
        jobs = [job_record(name)] if isinstance(name, str) else []
        data = ls_output(logs=[log_record(file_name), log_record("ok1.log")], jobs=jobs)
        listing = parse_ls_output(data)
        assert [log.name for log in listing.job_logs] == ["ok1"]
        assert listing.other_in_logs == 1

    @pytest.mark.parametrize(
        "file_name",
        ["train1", "train1.LOG", "train1.log.bak", "train1.txt", ".log", "train1.log ", "log"],
        ids=repr,
    )
    def test_file_without_log_suffix_is_other(self, file_name: str) -> None:
        data = ls_output(logs=[log_record(file_name)])
        listing = parse_ls_output(data)
        assert listing.job_logs == ()
        assert listing.other_in_logs == 1

    @pytest.mark.parametrize("name", ["a", "A1", "x" * 64, "a_b-c", "train1"])
    def test_good_job_name_is_listed(self, name: str) -> None:
        listing = parse_ls_output(ls_output(logs=[log_record(name + ".log")]))
        assert [log.name for log in listing.job_logs] == [name]

    def test_bad_job_session_does_not_make_anything_running(self) -> None:
        """規則に合わない名前のセッションは，規則に合うログを実行中にしない."""
        data = ls_output(
            logs=[log_record("train1.log")],
            jobs=[job_record("train1\n"), job_record("train1 "), job_record(" train1")],
        )
        assert parse_ls_output(data).job_logs == (JobLogEntry("train1", 10, False),)

    def test_bad_names_are_not_anywhere_in_listing(self) -> None:
        """規則に合わない名前は，結果のどこにも残らない（件数だけ）."""
        # 実験 ID としてもジョブ名としても規則に合わない名前（`nul` 等はジョブ名としては正しい）
        names = [n for n in BAD_JOB_NAMES if isinstance(n, str) and n and n in BAD_RUN_IDS]
        data = ls_output(
            results=[dir_record(n) for n in names],
            logs=[log_record(n + ".log") for n in names],
            jobs=[job_record(n) for n in names],
        )
        listing = parse_ls_output(data)
        assert listing.run_dirs == () and listing.job_logs == ()
        assert listing.other_in_results == len(names)
        assert listing.other_in_logs == len(names)
        text = repr(listing)
        for n in names:
            if len(n) > 3:
                assert repr(n)[1:-1] not in text


# ---------------------------------------------------------------------------
# 全サーバの要約
# ---------------------------------------------------------------------------


def _ok(name: str, *, complete: bool = True, run_ids: tuple[str, ...] = ()) -> ServerLeftovers:
    runs = tuple(RunDirEntry(r, 1, 1, complete) for r in run_ids) or (
        (RunDirEntry(RUN_A, 1, 1, False),) if not complete else ()
    )
    return ServerLeftovers(name, RemoteListing(remote_dir_exists=True, run_dirs=runs))


class TestSummary:
    def test_all_ok(self) -> None:
        summary = summarize_ls([_ok("Newton"), _ok("Archimedes")])
        assert summary == LsSummary((), (), (), False)

    def test_classifies_each_server(self) -> None:
        results = [
            _ok("Newton"),
            ServerLeftovers("Archimedes", None, "接続不可", unreachable=True),
            ServerLeftovers("Curie", None, "解釈できない"),
            _ok("Darwin", complete=False),
            ServerLeftovers("Euler", RemoteListing(remote_dir_exists=True, sizes_complete=False)),
        ]
        summary = summarize_ls(results)
        assert summary.unreachable == ("Archimedes",)
        assert summary.unreadable == ("Curie",)
        assert summary.incomplete == ("Darwin", "Euler")
        assert not summary.all_unreachable

    def test_all_unreachable(self) -> None:
        results = [
            ServerLeftovers("Newton", None, "x", unreachable=True),
            ServerLeftovers("Archimedes", None, "y", unreachable=True),
        ]
        assert summarize_ls(results).all_unreachable

    def test_unreadable_is_not_unreachable(self) -> None:
        """接続できたが解釈できないサーバは，接続不可ではない（全台接続不可にならない）."""
        results = [
            ServerLeftovers("Newton", None, "x", unreachable=True),
            ServerLeftovers("Archimedes", None, "解釈できない"),
        ]
        summary = summarize_ls(results)
        assert not summary.all_unreachable
        assert summary.unreadable == ("Archimedes",)

    def test_empty_is_not_all_unreachable(self) -> None:
        assert not summarize_ls([]).all_unreachable

    def test_listed_run_ids_collects_all_servers(self) -> None:
        results = [
            _ok("Newton", run_ids=(RUN_A,)),
            _ok("Archimedes", run_ids=(RUN_A, RUN_B)),
            ServerLeftovers("Curie", None, "x", unreachable=True),
        ]
        assert listed_run_ids(results) == frozenset({RUN_A, RUN_B})
