"""回収ホワイトリストの判定のテスト（SPEC_01「回収ホワイトリスト」・SPEC_03「pull」）.

最重要（testing ルールの必須対象 1）: 名前が一致するファイルだけが回収対象になり，分割結果・
画像ごとの予測・画像・manifest・指定の無い重みは回収されないこと．破れるとファイル名を含む結果や
画像が手元に流れる．

回収する（`runs/<実験ID>/` 配下）: `config.yaml`・`history.csv`・`metrics.json`・`log.txt`・
`figures/*.png`（直下のみ）．`--with-checkpoints` のときだけ `checkpoints/best.pth`・
`checkpoints/ResUNet.onnx`（名前の完全一致）．それ以外はすべて回収しない．

TIASJudgeModel の tests/remote/test_whitelist.py の移植．回収するファイル名と重みの名前を
本リポジトリの SPEC_01 に合わせ，抜け道（`:`・末尾の `.` や空白・大文字小文字・制御文字・
ディレクトリのエントリ等）と，`tsm-train` の実験 ID の形の確認を足した．
"""

import io
import tarfile
from datetime import datetime

import pytest

from tongue_seg_model.remote.whitelist import (
    PULL_CHECKPOINT_FILES,
    PULL_ROOT_FILES,
    check_pull_members,
    is_pull_allowed,
    parse_find_listing,
    plan_pull,
    validate_run_id,
)

RUN_ID = "20261119-120000_resunet_abc1234"

# SPEC_01「回収ホワイトリスト」の表
ROOT_FILES = ["config.yaml", "history.csv", "metrics.json", "log.txt"]
FIGURES = ["figures/loss.png", "figures/iou.png", "figures/learning_curve.png", "figures/a b.png"]
CHECKPOINTS = ["checkpoints/best.pth", "checkpoints/ResUNet.onnx"]
ALLOWED = ROOT_FILES + FIGURES

# 列挙外（回収してはならない）ファイル．--with-checkpoints を付けても回収しない
NOT_ALLOWED = [
    # 画像ごとの結果・分割結果（ファイル名を含む）
    "split.json",
    "predictions.csv",
    "per_image_predictions.csv",
    "manifest.csv",
    "data/manifest.csv",
    # 画像（figures/ 以外にある *.png・figures/ の png 以外）
    "a.png",
    "loss.png",
    "P0001_tongue.png",
    "P0001_tongue.jpg",
    "images/P0001.png",
    "masks/P0001.png",
    "predictions/P0001.png",
    "figures/x.jpg",
    "figures/x.jpeg",
    "figures/x.bmp",
    "figures/x.npy",
    "figures/sub/a.png",
    "figures/a/b/c.png",
    "sub/figures/a.png",
    "figures/.png",
    "figures/config.yaml",
    # 名前の似たもの
    "config.yml",
    "config.yaml.bak",
    "config.yaml~",
    ".config.yaml",
    "metrics.json.tmp",
    "history.csv.bak",
    "log.txt.1",
    "sub/config.yaml",
    "checkpoints/config.yaml",
    # 大文字小文字の違い（完全一致で比べる）
    "Config.yaml",
    "CONFIG.YAML",
    "Metrics.json",
    "LOG.TXT",
    "figures/loss.PNG",
    "figures/loss.Png",
    "Figures/loss.png",
    "FIGURES/loss.png",
    # Windows が末尾の . や空白を捨てて別の名前になるもの
    "config.yaml.",
    "config.yaml ",
    "config.yaml. ",
    "figures/a.png.",
    "figures/a.png ",
    "figures./a.png",
    "figures /a.png",
    # 代替データストリーム・Windows で使えない文字
    "config.yaml:secret",
    "metrics.json::$DATA",
    "figures/a:b.png",
    "figures/a<b.png",
    "figures/a>b.png",
    'figures/a"b.png',
    "figures/a|b.png",
    "figures/a?b.png",
    "figures/a*b.png",
    # 制御文字・改行
    "config.yaml\n",
    "figures/a\n.png",
    "figures/a\r.png",
    "figures/a\x00.png",
    "figures/a\t.png",
    "figures/a\x1b.png",
    "figures/a\x7f.png",
    # 重み（指定の無いもの・名前が完全一致しないもの）
    "checkpoints/epoch3.pth",
    "checkpoints/last.pth",
    "checkpoints/resunet.onnx",
    "checkpoints/RESUNET.ONNX",
    "checkpoints/Best.pth",
    "checkpoints/best.PTH",
    "checkpoints/best.pt",
    "checkpoints/best.pth.",
    "checkpoints/best.pth ",
    "checkpoints/best.pth.bak",
    "checkpoints/sub/best.pth",
    "checkpoints/figures/a.png",
    "Checkpoints/best.pth",
    "best.pth",
    "ResUNet.onnx",
    "figures/best.pth",
    "figures/ResUNet.onnx",
]

UNSAFE_PATHS = [
    "..",
    "../config.yaml",
    "../x/config.yaml",
    "figures/../config.yaml",
    "figures/../split.json",
    "./config.yaml",
    "figures/./a.png",
    "figures//a.png",
    "/config.yaml",
    "/etc/passwd",
    "C:config.yaml",
    "C:/config.yaml",
    "c:/figures/a.png",
    "figures\\a.png",
    "..\\config.yaml",
    "\\\\server\\share\\config.yaml",
    "",
    "/",
    "figures/",
    "checkpoints/../checkpoints/best.pth",
]


def test_root_files_are_exactly_the_spec_list() -> None:
    # 回収対象を増やすときは SPEC_01 とこのテストを同時に変える
    assert PULL_ROOT_FILES == frozenset(ROOT_FILES)


def test_checkpoint_files_are_exactly_the_spec_list() -> None:
    assert PULL_CHECKPOINT_FILES == frozenset({"best.pth", "ResUNet.onnx"})


class TestIsPullAllowed:
    @pytest.mark.parametrize("name", ALLOWED)
    @pytest.mark.parametrize("with_checkpoints", [False, True])
    def test_allowed_names(self, name: str, with_checkpoints: bool) -> None:
        assert is_pull_allowed(name, with_checkpoints=with_checkpoints)

    @pytest.mark.parametrize("name", NOT_ALLOWED)
    @pytest.mark.parametrize("with_checkpoints", [False, True])
    def test_names_outside_whitelist_are_not_allowed(
        self, name: str, with_checkpoints: bool
    ) -> None:
        # --with-checkpoints は checkpoints/best.pth・ResUNet.onnx 以外の判定を変えない
        assert not is_pull_allowed(name, with_checkpoints=with_checkpoints)

    @pytest.mark.parametrize("name", ["split.json", "predictions.csv", "manifest.csv"])
    def test_per_image_results_never_pulled_even_with_checkpoints(self, name: str) -> None:
        assert not is_pull_allowed(name, with_checkpoints=True)

    @pytest.mark.parametrize("name", CHECKPOINTS)
    def test_checkpoints_only_with_flag(self, name: str) -> None:
        assert not is_pull_allowed(name, with_checkpoints=False)
        assert is_pull_allowed(name, with_checkpoints=True)

    @pytest.mark.parametrize("name", UNSAFE_PATHS)
    def test_unsafe_paths_are_not_allowed(self, name: str) -> None:
        assert not is_pull_allowed(name, with_checkpoints=True)


class TestValidateRunId:
    @pytest.mark.parametrize(
        "run_id",
        [
            RUN_ID,
            "20261119-120000_resunet_abc1234-dirty",
            "20261119-120000_synthetic-gpu_nogit",
            "20261119-120000_my.config_0123456789abcdef0123456789abcdef01234567-dirty",
            "a",
            "A" * 200,
        ],
    )
    def test_accepts_normal_run_id(self, run_id: str) -> None:
        assert validate_run_id(run_id) == run_id

    @pytest.mark.parametrize(
        "run_id",
        [
            "a/b",
            "a\\b",
            "..",
            "../x",
            "x/..",
            "a..b",
            "/abs",
            "runs/x",
            "",
            ".",
            ".hidden",
            "-rf",
            "_x",
            # 末尾の改行（match と $ の組み合わせでは通ってしまう）
            f"{RUN_ID}\n",
            f"{RUN_ID}\r",
            f"\n{RUN_ID}",
            f"{RUN_ID} ",
            f" {RUN_ID}",
            "a b",
            "a'b",
            'a"b',
            "a;b",
            "a$b",
            "$(id)",
            "`id`",
            "a:b",
            "C:x",
            "a*",
            "a\x00b",
            "a\tb",
            "実験",
            "A" * 201,
        ],
    )
    def test_rejects_bad_run_id(self, run_id: str) -> None:
        with pytest.raises(ValueError):
            validate_run_id(run_id)

    def test_error_is_value_error_with_hint(self) -> None:
        with pytest.raises(ValueError, match="実験 ID"):
            validate_run_id("../x")


class TestRunIdOfTsmTrain:
    """`tsm-train` の実験 ID（`make_run_id`）が pull の実験 ID の検証を通ること.

    `remote` から `training` を import してはならないが，テストコードからは使ってよい．
    """

    @pytest.mark.parametrize(
        ("config_name", "git_commit"),
        [
            ("resunet", "abc1234"),
            ("resunet", "abc1234-dirty"),
            ("synthetic", "nogit"),
            ("synthetic-gpu", "0123456789abcdef0123456789abcdef01234567-dirty"),
            ("my.config_v2", "deadbeef"),
            ("C" * 64, "a" * 64),
        ],
    )
    def test_make_run_id_passes(self, config_name: str, git_commit: str) -> None:
        from tongue_seg_model.training.run_artifacts import make_run_id

        run_id = make_run_id(datetime(2026, 11, 19, 12, 0, 0), config_name, git_commit)
        assert validate_run_id(run_id) == run_id

    def test_value_passed_by_remote_is_accepted_by_training(self) -> None:
        """`format_git_commit` が渡す値を `resolve_git_commit` がそのまま受け取ること."""
        from tongue_seg_model.remote.commands import format_git_commit
        from tongue_seg_model.training.run_artifacts import make_run_id, resolve_git_commit

        for short_hash in ["abc1", "abc1234", "0123456789abcdef0123456789abcdef01234567"]:
            for dirty in (False, True):
                value = format_git_commit(short_hash, dirty=dirty)
                assert value is not None
                assert resolve_git_commit({"TSM_GIT_COMMIT": value}) == value
                run_id = make_run_id(datetime(2026, 1, 2, 3, 4, 5), "resunet", value)
                assert validate_run_id(run_id) == run_id


def test_git_commit_env_var_is_the_same_in_remote_and_training() -> None:
    """`TSM_GIT_COMMIT` の名前は 2 か所に置かれている（remote は training を import しないため）."""
    from tongue_seg_model.remote import commands
    from tongue_seg_model.training import run_artifacts

    assert commands.GIT_COMMIT_ENV_VAR == run_artifacts.GIT_COMMIT_ENV_VAR == "TSM_GIT_COMMIT"


class TestPlanPull:
    def _listing(self, names: list[str], kind: str = "f") -> list[tuple[str, str]]:
        return [(kind, f"{RUN_ID}/{name}") for name in names]

    def test_selects_only_whitelisted_files(self) -> None:
        listing = self._listing(ALLOWED + NOT_ALLOWED + CHECKPOINTS)
        plan = plan_pull(listing, RUN_ID, with_checkpoints=False)
        assert sorted(plan.files) == sorted(f"{RUN_ID}/{name}" for name in ALLOWED)
        assert plan.skipped == len(NOT_ALLOWED) + len(CHECKPOINTS)
        assert plan.skipped_checkpoints == len(CHECKPOINTS)

    def test_with_checkpoints_includes_only_two_weights(self) -> None:
        listing = self._listing(
            ["config.yaml", *CHECKPOINTS, "checkpoints/epoch3.pth", "split.json", "predictions.csv"]
        )
        plan = plan_pull(listing, RUN_ID, with_checkpoints=True)
        assert sorted(plan.files) == sorted(
            [f"{RUN_ID}/config.yaml", *(f"{RUN_ID}/{name}" for name in CHECKPOINTS)]
        )
        assert plan.skipped == 3
        assert plan.skipped_checkpoints == 0

    @pytest.mark.parametrize("kind", ["l", "d", "p", "s", "c", "b", "D", "N", "?"])
    def test_non_regular_entries_are_not_selected_even_with_whitelisted_name(
        self, kind: str
    ) -> None:
        listing = self._listing(["config.yaml", "figures/a.png", "checkpoints/best.pth"], kind)
        plan = plan_pull(listing, RUN_ID, with_checkpoints=True)
        assert plan.files == ()
        assert plan.skipped == 3

    @pytest.mark.parametrize(
        "path",
        [
            "other_run/config.yaml",
            f"{RUN_ID}x/config.yaml",
            f"{RUN_ID.upper()}/config.yaml",
            "config.yaml",
            f"{RUN_ID}",
            f"x/{RUN_ID}/config.yaml",
            f"../{RUN_ID}/config.yaml",
        ],
    )
    def test_files_outside_the_run_are_not_selected(self, path: str) -> None:
        plan = plan_pull([("f", path)], RUN_ID, with_checkpoints=True)
        assert plan.files == ()
        assert plan.skipped == 1

    def test_parse_find_listing_round_trip(self) -> None:
        data = f"f {RUN_ID}/config.yaml\0f {RUN_ID}/figures/a b.png\0l {RUN_ID}/x\0".encode()
        assert parse_find_listing(data) == [
            ("f", f"{RUN_ID}/config.yaml"),
            ("f", f"{RUN_ID}/figures/a b.png"),
            ("l", f"{RUN_ID}/x"),
        ]

    def test_newline_in_server_file_name_does_not_split_entries(self) -> None:
        # NUL 区切りなので，改行を含む名前で別のエントリを偽装できない
        data = f"f {RUN_ID}/split.json\nf {RUN_ID}/config.yaml\0".encode()
        listing = parse_find_listing(data)
        assert len(listing) == 1
        assert plan_pull(listing, RUN_ID, with_checkpoints=False).files == ()

    def test_non_utf8_names_are_not_selected(self) -> None:
        data = b"f " + RUN_ID.encode() + b"/figures/\xff\xfe.png\0"
        listing = parse_find_listing(data)
        plan = plan_pull(listing, RUN_ID, with_checkpoints=False)
        # 名前としては figures/*.png に一致する．選ばれたなら tar の側でも同じ名前で検査される
        assert len(plan.files) + plan.skipped == 1

    @pytest.mark.parametrize("data", [b"fconfig.yaml\0", b" x\0", b"f \0"])
    def test_broken_listing_is_error(self, data: bytes) -> None:
        with pytest.raises(ValueError):
            parse_find_listing(data)


def _regular(name: str) -> tarfile.TarInfo:
    info = tarfile.TarInfo(name)
    info.size = 0
    return info


def _typed(name: str, kind: bytes, target: str = "") -> tarfile.TarInfo:
    info = tarfile.TarInfo(name)
    info.type = kind
    info.linkname = target
    return info


BAD_MEMBERS = [
    *(_regular(f"{RUN_ID}/{name}") for name in NOT_ALLOWED),
    *(_regular(f"{RUN_ID}/{name}") for name in UNSAFE_PATHS),
    *(_regular(name) for name in UNSAFE_PATHS),
    _regular("other_run/config.yaml"),
    _regular("config.yaml"),
    _regular(f"{RUN_ID.upper()}/config.yaml"),
    _regular(f"{RUN_ID}/../config.yaml"),
    _regular(f"{RUN_ID}/../../x/config.yaml"),
    _regular(f"/{RUN_ID}/config.yaml"),
    _regular(f"C:/{RUN_ID}/config.yaml"),
    _regular(f"C:{RUN_ID}/config.yaml"),
    _regular(f"{RUN_ID}\\config.yaml"),
    _regular(f"{RUN_ID}/config.yaml:stream"),
    _typed(f"{RUN_ID}/config.yaml", tarfile.SYMTYPE, "/etc/passwd"),
    _typed(f"{RUN_ID}/figures/a.png", tarfile.SYMTYPE, "../split.json"),
    _typed(f"{RUN_ID}/metrics.json", tarfile.LNKTYPE, f"{RUN_ID}/config.yaml"),
    _typed(f"{RUN_ID}/log.txt", tarfile.LNKTYPE, f"{RUN_ID}/split.json"),
    _typed(f"{RUN_ID}/figures", tarfile.DIRTYPE),
    _typed(RUN_ID, tarfile.DIRTYPE),
    _typed(f"{RUN_ID}/config.yaml", tarfile.DIRTYPE),
    _typed(f"{RUN_ID}/config.yaml", tarfile.FIFOTYPE),
    _typed(f"{RUN_ID}/config.yaml", tarfile.CHRTYPE),
    _typed(f"{RUN_ID}/config.yaml", tarfile.BLKTYPE),
]


class TestCheckPullMembers:
    def test_accepts_only_whitelisted_regular_files(self) -> None:
        members = [_regular(f"{RUN_ID}/{name}") for name in ALLOWED]
        assert check_pull_members(members, RUN_ID, with_checkpoints=False) == len(members)

    def test_accepts_checkpoints_with_flag(self) -> None:
        members = [_regular(f"{RUN_ID}/{name}") for name in ALLOWED + CHECKPOINTS]
        assert check_pull_members(members, RUN_ID, with_checkpoints=True) == len(members)

    def test_empty_archive_is_accepted_as_zero(self) -> None:
        assert check_pull_members([], RUN_ID, with_checkpoints=False) == 0

    @pytest.mark.parametrize("bad", BAD_MEMBERS, ids=lambda info: repr(info.name)[:60])
    @pytest.mark.parametrize("with_checkpoints", [False, True])
    def test_rejects_whole_archive_if_any_member_is_bad(
        self, bad: tarfile.TarInfo, with_checkpoints: bool
    ) -> None:
        members = [_regular(f"{RUN_ID}/config.yaml"), bad, _regular(f"{RUN_ID}/log.txt")]
        with pytest.raises(ValueError):
            check_pull_members(members, RUN_ID, with_checkpoints=with_checkpoints)

    @pytest.mark.parametrize("name", CHECKPOINTS)
    def test_checkpoints_rejected_without_flag(self, name: str) -> None:
        members = [_regular(f"{RUN_ID}/config.yaml"), _regular(f"{RUN_ID}/{name}")]
        with pytest.raises(ValueError):
            check_pull_members(members, RUN_ID, with_checkpoints=False)

    def test_error_message_does_not_contain_member_names(self) -> None:
        secret = "P0001_yamada_tongue"
        members = [
            _regular(f"{RUN_ID}/{secret}.png"),
            _regular(f"{RUN_ID}/figures/{secret}:x.png"),
            _typed(f"{RUN_ID}/{secret}_link", tarfile.SYMTYPE, f"/home/{secret}"),
            _typed(f"{RUN_ID}/{secret}_dir", tarfile.DIRTYPE),
            _regular(f"../{secret}.csv"),
            _regular(f"{RUN_ID}/checkpoints/{secret}.pth"),
        ]
        with pytest.raises(ValueError) as excinfo:
            check_pull_members(members, RUN_ID, with_checkpoints=False)
        message = str(excinfo.value)
        assert secret not in message
        assert "yamada" not in message
        assert RUN_ID not in message
        # 件数だけを示す
        assert "ホワイトリスト外" in message

    def test_members_from_real_tar_file(self) -> None:
        buffer = io.BytesIO()
        with tarfile.open(fileobj=buffer, mode="w") as tar:
            tar.addfile(_regular(f"{RUN_ID}/config.yaml"), io.BytesIO(b""))
            tar.addfile(_typed(f"{RUN_ID}/log.txt", tarfile.SYMTYPE, "/etc/shadow"))
        buffer.seek(0)
        with tarfile.open(fileobj=buffer, mode="r") as tar, pytest.raises(ValueError):
            check_pull_members(tar.getmembers(), RUN_ID, with_checkpoints=False)

    def test_pax_path_override_is_checked(self) -> None:
        """PAX ヘッダの path で名前を差し替えたメンバーも，差し替え後の名前で検査する."""
        buffer = io.BytesIO()
        with tarfile.open(fileobj=buffer, mode="w", format=tarfile.PAX_FORMAT) as tar:
            info = _regular(f"{RUN_ID}/config.yaml")
            info.pax_headers = {"path": f"{RUN_ID}/split.json"}
            tar.addfile(info, io.BytesIO(b""))
        buffer.seek(0)
        with tarfile.open(fileobj=buffer, mode="r") as tar:
            members = tar.getmembers()
            assert members[0].name == f"{RUN_ID}/split.json"
            with pytest.raises(ValueError):
                check_pull_members(members, RUN_ID, with_checkpoints=True)


# ---------------------------------------------------------------------------
# Windows で見かけと違う場所を指す名前（末尾の `.`・空白と予約デバイス名）
# ---------------------------------------------------------------------------

# 予約名: CON・PRN・AUX・NUL・COM1〜9・LPT1〜9・COM¹〜³・LPT¹〜³（大文字小文字を問わず，
# 最初の `.` より前で判定する）
RESERVED_BASES = [
    "CON",
    "con",
    "Prn",
    "aux",
    "NUL",
    "nul",
    *(f"COM{d}" for d in "123456789"),
    *(f"lpt{d}" for d in "123456789"),
    "COM¹",
    "com²",
    "COM³",
    "LPT¹",
    "lpt²",
    "LPT³",
]
# 予約名に似ているが予約名ではないもの
NOT_RESERVED_BASES = ["CONSOLE", "COM10", "LPT10", "COM0", "LPT0", "nul_", "_nul", "CONx", "AUX1"]


class TestWindowsUnsafeRunId:
    @pytest.mark.parametrize(
        "run_id",
        [
            "abc.",
            "abc..",
            "nul",
            "NUL",
            "con.txt",
            "Com1",
            "lpt9.x",
            "AUX",
            "prn.tar.gz",
            "COM¹",
            "lpt³.a",
            f"{RUN_ID}.",
        ],
    )
    def test_rejects_trailing_dot_and_reserved_names(self, run_id: str) -> None:
        with pytest.raises(ValueError):
            validate_run_id(run_id)

    @pytest.mark.parametrize(
        "run_id",
        ["CONSOLE", "COM10", "LPT10", "COM0", "nul_", "CONx", "AUX1", "CONSOLE.x", "nul_.a"],
    )
    def test_names_similar_to_reserved_are_accepted(self, run_id: str) -> None:
        assert validate_run_id(run_id) == run_id

    @pytest.mark.parametrize(
        "run_id",
        [
            "20261119-120000_resunet_abc1234-dirty",
            "20261119-120000_synthetic_nogit",
            "20261119-120000_resunet_0123456789abcdef0123456789abcdef01234567",
            "20261119-120000_con_abc1234",
            "20261119-120000_nul_nogit",
        ],
    )
    def test_make_run_id_shapes_are_still_accepted(self, run_id: str) -> None:
        assert validate_run_id(run_id) == run_id

    @pytest.mark.parametrize("config_name", ["con", "NUL", "aux", "com1", "lpt9", "prn"])
    def test_make_run_id_with_reserved_like_config_name_passes(self, config_name: str) -> None:
        """設定ファイル名が予約名でも実験 ID 全体は予約名にならない（日時で始まる）."""
        from tongue_seg_model.training.run_artifacts import make_run_id

        run_id = make_run_id(datetime(2026, 11, 19, 12, 0, 0), config_name, "abc1234-dirty")
        assert validate_run_id(run_id) == run_id


class TestWindowsUnsafePullNames:
    @pytest.mark.parametrize(
        "name",
        [
            "figures/CON.png",
            "figures/nul.png",
            "figures/COM1.png",
            "figures/LPT9.png",
            "figures/Aux.x.png",
            "figures/nul .png",
            "figures/PRN.png",
            "figures/com¹.png",
            "figures/LPT³.png",
            "figures/a.png.",
            "figures/a.png ",
            "figures./a.png",
            "figures /a.png",
        ],
    )
    @pytest.mark.parametrize("with_checkpoints", [False, True])
    def test_reserved_or_trailing_dot_names_are_not_pulled(
        self, name: str, with_checkpoints: bool
    ) -> None:
        assert not is_pull_allowed(name, with_checkpoints=with_checkpoints)

    @pytest.mark.parametrize(
        "name",
        [
            "figures/CONSOLE.png",
            "figures/COM10.png",
            "figures/nul_.png",
            "figures/LPT10.png",
            "figures/con_matrix.png",
            "figures/a.b.png",
        ],
    )
    def test_names_similar_to_reserved_are_pulled(self, name: str) -> None:
        assert is_pull_allowed(name, with_checkpoints=False)

    @pytest.mark.parametrize("base", RESERVED_BASES)
    def test_every_reserved_base_is_rejected(self, base: str) -> None:
        assert not is_pull_allowed(f"figures/{base}.png", with_checkpoints=True)

    @pytest.mark.parametrize("base", NOT_RESERVED_BASES)
    def test_every_not_reserved_base_is_accepted(self, base: str) -> None:
        assert is_pull_allowed(f"figures/{base}.png", with_checkpoints=False)

    def test_plan_pull_skips_reserved_names(self) -> None:
        listing = [
            ("f", f"{RUN_ID}/config.yaml"),
            ("f", f"{RUN_ID}/figures/CON.png"),
            ("f", f"{RUN_ID}/figures/nul .png"),
            ("f", f"{RUN_ID}/figures/CONSOLE.png"),
        ]
        plan = plan_pull(listing, RUN_ID, with_checkpoints=False)
        assert plan.files == (f"{RUN_ID}/config.yaml", f"{RUN_ID}/figures/CONSOLE.png")
        assert plan.skipped == 2


class TestWindowsUnsafeTarMembers:
    @pytest.mark.parametrize(
        "name",
        [
            f"{RUN_ID}/figures/CON.png",
            f"{RUN_ID}/figures/nul.png",
            f"{RUN_ID}/figures/COM1.png",
            f"{RUN_ID}/figures/LPT9.png",
            f"{RUN_ID}/figures/Aux.x.png",
            f"{RUN_ID}/figures/nul .png",
            f"{RUN_ID}/figures/a.png.",
            f"{RUN_ID}/config.yaml.",
            f"{RUN_ID}/figures./a.png",
            f"{RUN_ID}./config.yaml",
            f"{RUN_ID}/figures/com².png",
        ],
    )
    @pytest.mark.parametrize("with_checkpoints", [False, True])
    def test_whole_archive_is_rejected(self, name: str, with_checkpoints: bool) -> None:
        members = [_regular(f"{RUN_ID}/config.yaml"), _regular(name), _regular(f"{RUN_ID}/log.txt")]
        with pytest.raises(ValueError):
            check_pull_members(members, RUN_ID, with_checkpoints=with_checkpoints)

    def test_names_similar_to_reserved_are_accepted(self) -> None:
        members = [
            _regular(f"{RUN_ID}/figures/CONSOLE.png"),
            _regular(f"{RUN_ID}/figures/COM10.png"),
            _regular(f"{RUN_ID}/figures/nul_.png"),
        ]
        assert check_pull_members(members, RUN_ID, with_checkpoints=False) == 3

    def test_error_message_does_not_contain_reserved_member_names(self) -> None:
        members = [_regular(f"{RUN_ID}/figures/P0001_yamada.png."), _regular(f"{RUN_ID}/nul.txt")]
        with pytest.raises(ValueError) as excinfo:
            check_pull_members(members, RUN_ID, with_checkpoints=False)
        assert "yamada" not in str(excinfo.value)
        assert "nul" not in str(excinfo.value)
