"""回収した tar の検査・展開のテスト（SPEC_03「pull」の二重の防御の 2 段目）.

受け取った tar にホワイトリスト外の名前・パス外に出る名前・リンクが 1 つでもあれば，
何も展開せずに中止すること（展開先に何も作られないこと）．

TIASJudgeModel の tests/remote/test_transfer.py の移植．重みの名前（`checkpoints/best.pth`・
`checkpoints/ResUNet.onnx`）と，TongueSegModel で回収しない名前（`split.json`・`predictions.csv`・
`figures/` 以外の画像・指定の無い重み）・抜け道（`:`・制御文字・ディレクトリのエントリ等）を足した．
"""

import io
import tarfile
from collections.abc import Iterator
from pathlib import Path

import pytest
from link_helpers import LinkFactory

from labremote.files import PushEntry
from labremote.transfer import extract_pull_archive, write_tar_stream

RUN_ID = "20261119-120000_resunet_abc1234-dirty"


def _add_file(tar: tarfile.TarFile, name: str, data: bytes = b"x") -> None:
    info = tarfile.TarInfo(name)
    info.size = len(data)
    tar.addfile(info, io.BytesIO(data))


def _add_link(tar: tarfile.TarFile, name: str, target: str, kind: bytes) -> None:
    info = tarfile.TarInfo(name)
    info.type = kind
    info.linkname = target
    tar.addfile(info)


def _add_dir(tar: tarfile.TarFile, name: str) -> None:
    info = tarfile.TarInfo(name)
    info.type = tarfile.DIRTYPE
    info.mode = 0o755
    tar.addfile(info)


def _archive(build) -> io.BytesIO:
    buffer = io.BytesIO()
    with tarfile.open(fileobj=buffer, mode="w", format=tarfile.PAX_FORMAT) as tar:
        build(tar)
    buffer.seek(0)
    return buffer


def _all_files(root: Path) -> list[Path]:
    return sorted(root.rglob("*")) if root.exists() else []


def test_extracts_whitelisted_files(tmp_path: Path) -> None:
    def build(tar: tarfile.TarFile) -> None:
        _add_file(tar, f"{RUN_ID}/config.yaml", b"seed: 0\n")
        _add_file(tar, f"{RUN_ID}/metrics.json", b"{}")
        _add_file(tar, f"{RUN_ID}/figures/loss.png", b"png")

    dest = tmp_path / "runs"
    result = extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False)
    assert result.files == 3
    assert (dest / RUN_ID / "config.yaml").read_bytes() == b"seed: 0\n"
    assert (dest / RUN_ID / "figures" / "loss.png").read_bytes() == b"png"


def test_overwrites_existing_file(tmp_path: Path) -> None:
    dest = tmp_path / "runs"
    (dest / RUN_ID).mkdir(parents=True)
    (dest / RUN_ID / "metrics.json").write_bytes(b"old")
    archive = _archive(lambda tar: _add_file(tar, f"{RUN_ID}/metrics.json", b"new"))
    extract_pull_archive(archive, dest, RUN_ID, with_checkpoints=False)
    assert (dest / RUN_ID / "metrics.json").read_bytes() == b"new"


def test_checkpoints_extracted_only_with_flag(tmp_path: Path) -> None:
    def build(tar: tarfile.TarFile) -> None:
        _add_file(tar, f"{RUN_ID}/config.yaml")
        _add_file(tar, f"{RUN_ID}/checkpoints/best.pth", b"weights")
        _add_file(tar, f"{RUN_ID}/checkpoints/ResUNet.onnx", b"onnx")

    dest = tmp_path / "runs"
    with pytest.raises(ValueError):
        extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False)
    assert _all_files(dest) == []

    result = extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=True)
    assert result.files == 3
    assert (dest / RUN_ID / "checkpoints" / "best.pth").read_bytes() == b"weights"
    assert (dest / RUN_ID / "checkpoints" / "ResUNet.onnx").read_bytes() == b"onnx"


BAD_MEMBERS = {
    "split_json": lambda tar: _add_file(tar, f"{RUN_ID}/split.json"),
    "split_json_in_figures": lambda tar: _add_file(tar, f"{RUN_ID}/figures/split.json"),
    "other_weight": lambda tar: _add_file(tar, f"{RUN_ID}/checkpoints/epoch3.pth"),
    "onnx_lowercase": lambda tar: _add_file(tar, f"{RUN_ID}/checkpoints/resunet.onnx"),
    "upper_case_config": lambda tar: _add_file(tar, f"{RUN_ID}/Config.yaml"),
    "upper_case_png": lambda tar: _add_file(tar, f"{RUN_ID}/figures/loss.PNG"),
    "png_in_sub_figures": lambda tar: _add_file(tar, f"{RUN_ID}/figures/sub/a.png"),
    "jpg_in_figures": lambda tar: _add_file(tar, f"{RUN_ID}/figures/x.jpg"),
    "empty_png_name": lambda tar: _add_file(tar, f"{RUN_ID}/figures/.png"),
    "trailing_dot": lambda tar: _add_file(tar, f"{RUN_ID}/figures/a.png."),
    "trailing_space": lambda tar: _add_file(tar, f"{RUN_ID}/config.yaml "),
    "alternate_stream": lambda tar: _add_file(tar, f"{RUN_ID}/figures/a:b.png"),
    "stream_on_config": lambda tar: _add_file(tar, f"{RUN_ID}/config.yaml:x"),
    "newline": lambda tar: _add_file(tar, f"{RUN_ID}/figures/a\n.png"),
    "control_char": lambda tar: _add_file(tar, f"{RUN_ID}/figures/a\x01.png"),
    "dotdot_in_figures": lambda tar: _add_file(tar, f"{RUN_ID}/figures/../split.json"),
    "absolute_etc": lambda tar: _add_file(tar, "/etc/passwd"),
    "drive_config": lambda tar: _add_file(tar, "C:/config.yaml"),
    "directory": lambda tar: _add_dir(tar, f"{RUN_ID}/figures"),
    "run_directory": lambda tar: _add_dir(tar, RUN_ID),
    "symlink_png": lambda tar: _add_link(
        tar, f"{RUN_ID}/figures/a.png", "../split.json", tarfile.SYMTYPE
    ),
    "hardlink_to_outside": lambda tar: _add_link(
        tar, f"{RUN_ID}/log.txt", "../../outside.txt", tarfile.LNKTYPE
    ),
    "fifo": lambda tar: _add_link(tar, f"{RUN_ID}/history.csv", "", tarfile.FIFOTYPE),
    "predictions": lambda tar: _add_file(tar, f"{RUN_ID}/predictions.csv"),
    "png_outside_figures": lambda tar: _add_file(tar, f"{RUN_ID}/P0001.png"),
    "manifest": lambda tar: _add_file(tar, f"{RUN_ID}/manifest.csv"),
    "image": lambda tar: _add_file(tar, f"{RUN_ID}/images/P0001.jpg"),
    "other_run": lambda tar: _add_file(tar, "other_run/config.yaml"),
    "dotdot": lambda tar: _add_file(tar, f"{RUN_ID}/../evil.txt"),
    "dotdot_top": lambda tar: _add_file(tar, "../evil.txt"),
    "absolute": lambda tar: _add_file(tar, "/tmp/evil.txt"),
    "drive_letter": lambda tar: _add_file(tar, "C:/evil.txt"),
    "drive_relative": lambda tar: _add_file(tar, "C:evil.txt"),
    "backslash": lambda tar: _add_file(tar, f"{RUN_ID}\\config.yaml"),
    "symlink": lambda tar: _add_link(tar, f"{RUN_ID}/log.txt", "/etc/passwd", tarfile.SYMTYPE),
    "symlink_relative": lambda tar: _add_link(
        tar, f"{RUN_ID}/history.csv", "../../outside", tarfile.SYMTYPE
    ),
    "hardlink": lambda tar: _add_link(
        tar, f"{RUN_ID}/metrics.json", f"{RUN_ID}/config.yaml", tarfile.LNKTYPE
    ),
}


@pytest.mark.parametrize("bad", list(BAD_MEMBERS), ids=list(BAD_MEMBERS))
@pytest.mark.parametrize("position", ["first", "last"])
def test_bad_member_aborts_without_extracting_anything(
    tmp_path: Path, bad: str, position: str
) -> None:
    def build(tar: tarfile.TarFile) -> None:
        if position == "first":
            BAD_MEMBERS[bad](tar)
        _add_file(tar, f"{RUN_ID}/config.yaml")
        _add_file(tar, f"{RUN_ID}/figures/cm.png")
        _add_file(tar, f"{RUN_ID}/checkpoints/best.pth")
        if position == "last":
            BAD_MEMBERS[bad](tar)

    work = tmp_path / "work"
    dest = work / "runs"
    with pytest.raises(ValueError):
        extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=True)
    # 展開先にも，その外側（パス外に出る名前の行き先）にも何も作られない
    assert _all_files(dest) == []
    assert not (dest / RUN_ID / "config.yaml").exists()
    assert not (work / "evil.txt").exists()
    assert not (tmp_path / "evil.txt").exists()
    assert [p for p in _all_files(tmp_path) if p.is_file()] == []


def test_error_message_does_not_contain_rejected_names(tmp_path: Path) -> None:
    secret = "P0001_yamada"

    def build(tar: tarfile.TarFile) -> None:
        _add_file(tar, f"{RUN_ID}/config.yaml")
        _add_file(tar, f"{RUN_ID}/{secret}.png")
        _add_file(tar, f"{RUN_ID}/figures/{secret}:a.png")
        _add_link(tar, f"{RUN_ID}/{secret}.lnk", f"/home/{secret}", tarfile.SYMTYPE)
        _add_dir(tar, f"{RUN_ID}/{secret}")

    with pytest.raises(ValueError) as excinfo:
        extract_pull_archive(_archive(build), tmp_path / "runs", RUN_ID, with_checkpoints=False)
    assert secret not in str(excinfo.value)
    assert "yamada" not in str(excinfo.value)


def test_broken_archive_extracts_nothing(tmp_path: Path) -> None:
    dest = tmp_path / "runs"
    with pytest.raises(tarfile.TarError):
        extract_pull_archive(io.BytesIO(b"not a tar" * 100), dest, RUN_ID, with_checkpoints=False)
    assert _all_files(dest) == []


def test_empty_archive_extracts_nothing(tmp_path: Path) -> None:
    result = extract_pull_archive(
        _archive(lambda tar: None), tmp_path / "runs", RUN_ID, with_checkpoints=False
    )
    assert result.files == 0


def test_write_tar_stream_round_trip(tmp_path: Path) -> None:
    src = tmp_path / "src"
    (src / "pkg").mkdir(parents=True)
    (src / "pkg" / "a.py").write_bytes(b"print('a')\n")
    (src / "日本語.md").write_text("x", encoding="utf-8")
    entries = [
        PushEntry(src / "pkg" / "a.py", "pkg/a.py", (src / "pkg" / "a.py").stat().st_size),
        PushEntry(src / "日本語.md", "日本語.md", 1),
    ]
    buffer = io.BytesIO()
    write_tar_stream(entries, buffer)
    buffer.seek(0)
    with tarfile.open(fileobj=buffer, mode="r") as tar:
        names = tar.getnames()
        assert names == ["pkg/a.py", "日本語.md"]
        member = tar.extractfile("pkg/a.py")
        assert member is not None
        assert member.read() == b"print('a')\n"


# ---------------------------------------------------------------------------
# write_tar_stream の二重の守り: 通常ファイル以外を含む entries は何も書かずに止める
# ---------------------------------------------------------------------------


@pytest.fixture
def links() -> Iterator[LinkFactory]:
    factory = LinkFactory()
    yield factory
    factory.cleanup()


def _entry(path: Path, arcname: str) -> PushEntry:
    return PushEntry(path, arcname, 0)


def _code_entry(root: Path) -> PushEntry:
    path = root / "a.py"
    path.write_bytes(b"print('a')\n")
    return PushEntry(path, "a.py", path.stat().st_size)


@pytest.mark.parametrize("position", ["first", "last"])
def test_write_tar_stream_rejects_file_symlink(
    tmp_path: Path, links: LinkFactory, position: str
) -> None:
    outside = tmp_path / "outside"
    outside.mkdir()
    (outside / "secret.py").write_bytes(b"secret")
    link = links.symlink(tmp_path / "leak.py", outside / "secret.py")
    good = _code_entry(tmp_path)
    bad = _entry(link, "leak.py")
    entries = [bad, good] if position == "first" else [good, bad]
    buffer = io.BytesIO()
    with pytest.raises(ValueError):
        write_tar_stream(entries, buffer)
    assert buffer.getvalue() == b""


@pytest.mark.parametrize("kind", ["symlink", "junction"])
def test_write_tar_stream_rejects_directory_link(
    tmp_path: Path, links: LinkFactory, kind: str
) -> None:
    outside = tmp_path / "outside"
    outside.mkdir()
    (outside / "secret.py").write_bytes(b"secret")
    link = getattr(links, kind)(tmp_path / "ext", outside)
    buffer = io.BytesIO()
    with pytest.raises(ValueError):
        write_tar_stream([_code_entry(tmp_path), _entry(link, "ext")], buffer)
    assert buffer.getvalue() == b""


def test_write_tar_stream_rejects_directory(tmp_path: Path) -> None:
    (tmp_path / "pkg").mkdir()
    buffer = io.BytesIO()
    with pytest.raises(ValueError):
        write_tar_stream([_code_entry(tmp_path), _entry(tmp_path / "pkg", "pkg")], buffer)
    assert buffer.getvalue() == b""


def test_write_tar_stream_rejects_missing_file(tmp_path: Path) -> None:
    buffer = io.BytesIO()
    with pytest.raises(ValueError):
        write_tar_stream([_code_entry(tmp_path), _entry(tmp_path / "gone.py", "gone.py")], buffer)
    assert buffer.getvalue() == b""


def test_write_tar_stream_does_not_dereference(tmp_path: Path) -> None:
    """通常ファイルだけの entries は従来どおりの tar になり，メンバーは通常ファイルのみ."""
    entries = [_code_entry(tmp_path)]
    buffer = io.BytesIO()
    assert write_tar_stream(entries, buffer) == entries[0].size
    buffer.seek(0)
    with tarfile.open(fileobj=buffer, mode="r") as tar:
        assert all(member.isreg() for member in tar.getmembers())


# ---------------------------------------------------------------------------
# 受け取った tar に Windows の予約名・末尾 `.` のエントリがあれば全体を拒否する
# ---------------------------------------------------------------------------


@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",
    ],
)
@pytest.mark.parametrize("position", ["first", "last"])
def test_windows_unsafe_member_aborts_without_extracting_anything(
    tmp_path: Path, name: str, position: str
) -> None:
    def build(tar: tarfile.TarFile) -> None:
        if position == "first":
            _add_file(tar, name)
        _add_file(tar, f"{RUN_ID}/config.yaml")
        _add_file(tar, f"{RUN_ID}/figures/CONSOLE.png")
        if position == "last":
            _add_file(tar, name)

    dest = tmp_path / "runs"
    with pytest.raises(ValueError):
        extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False)
    assert _all_files(dest) == []


def test_names_similar_to_reserved_are_extracted(tmp_path: Path) -> None:
    def build(tar: tarfile.TarFile) -> None:
        for name in ["CONSOLE.png", "COM10.png", "nul_.png"]:
            _add_file(tar, f"{RUN_ID}/figures/{name}")

    dest = tmp_path / "runs"
    result = extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False)
    assert result.files == 3
    assert sorted(p.name for p in (dest / RUN_ID / "figures").iterdir()) == [
        "COM10.png",
        "CONSOLE.png",
        "nul_.png",
    ]
