"""利用する側のテストのための関数（`labremote.testing`）のテスト（SPEC_01「プロジェクトの側のテスト」）.

送信・回収の規則そのもの（何が除外されるか）は `test_files.py`・`test_whitelist.py`・
`test_config.py` が確かめている．ここでは，この入口が実際の `push`・`pull` と同じ答えを返すことと，
入口に固有の決まり（`rel_path` の検証・途中のフォルダ・親を探さない・ファイルを見ない）を確かめる．
"""

from __future__ import annotations

import os
import re
import shutil
import subprocess
from pathlib import Path

import pytest
import yaml
from pydantic import ValidationError
from results_helpers import OTHER_RESULTS_YAML, SAMPLE_RESULTS_YAML

import labremote
import labremote.testing as testing_module
from labremote.config import RemoteConfig
from labremote.files import select_push_files
from labremote.testing import is_pulled, is_pushed, load_config
from labremote.whitelist import is_pull_allowed

# 接続先は架空の Host 名（.claude/rules/testing.md）
_BASE_YAML = """\
project:
  name: Sample
servers:
  - name: hostA
    priority: 1
    remote_dir: ~/work/Sample
"""

_PUSH_YAML = """\
push:
  exclude_root: [data, legacy]
  exclude_dirs: [scratch]
  exclude_suffixes: [.pth]
  partial:
    - path: external/Hub
      include: [pyproject.toml, src]
"""

# 実際の選別にかける，小さいプロジェクトのファイル（リンクと LabRemote 自身のフォルダは作らない）
_PROJECT_FILES = [
    # 送られるもの
    "README.md",
    "src/model.py",
    "src/data/x.py",  # exclude_root は直下だけ
    "src/legacy.py",
    "sub/labremote.yaml",  # 設定ファイルの除外はルートの直下だけ
    "models.pth/inner.py",  # フォルダには拡張子の除外を当てない
    "external/Hub/pyproject.toml",
    "external/Hub/src/a.py",
    "output/other.txt",
    # 固定の除外
    "labremote.yaml",
    ".git/config",
    "src/.git/x",
    "a/b/.venv/y",
    "src/__pycache__/m.pyc",
    ".claude/settings.json",
    ".env",
    "src/.env.local",
    # exclude_root
    "data/train/a.png",
    "legacy/old.txt",
    # exclude_dirs
    "src/scratch/tmp.py",
    "lib/scratch",  # 同じ名前のファイル
    # exclude_suffixes
    "src/w.pth",
    # partial の include に無いもの
    "external/Hub/README.md",
    "external/Hub/data/x.csv",
    # 結果の置き場（既定の runs と，output/runs）
    "runs/exp1/metrics.json",
    "output/runs/exp1/metrics.json",
]


def _write_config(root: Path, *sections: str) -> Path:
    root.mkdir(parents=True, exist_ok=True)
    path = root / "labremote.yaml"
    path.write_text(_BASE_YAML + "".join(sections), encoding="utf-8")
    return path


def _make_project(root: Path, *sections: str) -> RemoteConfig:
    for rel in _PROJECT_FILES:
        if rel == "labremote.yaml":
            continue
        target = root / rel
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text("x", encoding="utf-8")
    _write_config(root, *sections)
    return load_config(root)


def _actual_push(root: Path, config: RemoteConfig) -> set[str]:
    # cli._collect_entries と同じ引数（LabRemote 自身のフォルダは cli._labremote_repo_dir と同じ）
    selection = select_push_files(
        root,
        config.push,
        config_path=root / "labremote.yaml",
        labremote_dir=Path(labremote.__file__).resolve().parent.parent.parent,
        results_dir=config.results.dir,
    )
    return {entry.arcname for entry in selection.entries}


def _all_files(root: Path) -> list[str]:
    return sorted(p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file())


class TestSameAnswerAsPush:
    """SPEC_01: 判定は，`push` が実際に使う関数をそのまま呼ぶ（食い違いを作らない）."""

    @pytest.mark.parametrize(
        "sections",
        [
            pytest.param((_PUSH_YAML,), id="push-rules"),
            pytest.param((_PUSH_YAML, "results:\n  dir: output/runs\n"), id="results-dir"),
            pytest.param(("push: {}\n",), id="empty-push"),
        ],
    )
    def test_is_pushed_matches_select_push_files(
        self, tmp_path: Path, sections: tuple[str, ...]
    ) -> None:
        """SPEC_01: `is_pushed` の答えが，実際の選別が選んだファイルの集合と一致する."""
        config = _make_project(tmp_path, *sections)
        files = _all_files(tmp_path)
        actual = _actual_push(tmp_path, config)
        predicted = {rel for rel in files if is_pushed(config, rel)}
        assert predicted == actual
        # 前提: 送られるものと送られないものの両方がある
        assert actual
        assert set(files) - actual


# 回収の判定にかける名前（回収される名前・されない名前・重み）
_PULL_NAMES = [
    "config.yaml",
    "metrics.json",
    "figures/loss.png",
    "figures/sub/a.png",
    "images/a.png",
    "manifest.csv",
    "split.json",
    "Config.yaml",
    "checkpoints/best.pth",
    "checkpoints/last.pth",
    "summary.txt",
    "out/plots/a.svg",
    "weights/final.ckpt",
    "debug/a.png",
]


class TestSameAnswerAsPull:
    """SPEC_01: 判定は，`pull` が実際に使う関数をそのまま呼ぶ."""

    @pytest.mark.parametrize("results_yaml", [SAMPLE_RESULTS_YAML, OTHER_RESULTS_YAML])
    @pytest.mark.parametrize("with_checkpoints", [False, True])
    def test_is_pulled_matches_is_pull_allowed(
        self, tmp_path: Path, results_yaml: str, with_checkpoints: bool
    ) -> None:
        """SPEC_01: `is_pulled` の答えが，設定の `results` で呼んだ `is_pull_allowed` と一致する."""
        _write_config(tmp_path, "push: {}\n", results_yaml)
        config = load_config(tmp_path)
        answers = []
        for name in _PULL_NAMES:
            expected = is_pull_allowed(name, config.results, with_checkpoints=with_checkpoints)
            got = is_pulled(config, name, with_checkpoints=with_checkpoints)
            assert got == expected, name
            answers.append(got)
        # 前提: 回収される名前とされない名前の両方がある
        assert any(answers)
        assert not all(answers)

    @pytest.mark.parametrize("with_checkpoints", [False, True])
    def test_results_omitted_pulls_nothing(self, tmp_path: Path, with_checkpoints: bool) -> None:
        """SPEC_02: `results` を省略した設定では，何も回収されない."""
        _write_config(tmp_path, "push: {}\n")
        config = load_config(tmp_path)
        for name in _PULL_NAMES:
            assert not is_pulled(config, name, with_checkpoints=with_checkpoints), name


@pytest.fixture
def push_config(tmp_path: Path) -> RemoteConfig:
    _write_config(tmp_path, _PUSH_YAML)
    return load_config(tmp_path)


class TestParentFolderExclusion:
    """SPEC_01: 途中のフォルダが除外されていれば，その下のパスも送られないと答える."""

    @pytest.mark.parametrize(
        "rel_path",
        [
            "data/train/a.png",  # exclude_root
            "src/.git/x",  # 固定の除外のフォルダ
            "a/b/.venv/y",
            "src/scratch/deep/tmp.py",  # exclude_dirs
            "external/Hub/data/x.csv",  # partial の include に無いフォルダの下
            "runs/exp1/metrics.json",  # 結果の置き場
        ],
    )
    def test_path_under_excluded_folder_is_not_pushed(
        self, push_config: RemoteConfig, rel_path: str
    ) -> None:
        """SPEC_01: 除外されたフォルダの下のパスは送られない."""
        assert not is_pushed(push_config, rel_path)

    @pytest.mark.parametrize(
        ("rel_path", "expected"),
        [
            ("data", False),
            ("legacy", False),
            ("src/scratch", False),
            ("external/Hub/data", False),
            ("runs", False),
            ("src", True),
            ("external/Hub/src", True),
            ("models.pth", True),
        ],
    )
    def test_folder_itself(self, push_config: RemoteConfig, rel_path: str, expected: bool) -> None:
        """SPEC_01: `is_dir=True` でフォルダそのものを尋ねても同じ答えになる."""
        assert is_pushed(push_config, rel_path, is_dir=True) is expected

    @pytest.mark.parametrize(
        "rel_path",
        ["src/data/x.py", "sub/labremote.yaml", "src/legacy/a.py", "external/Hub/src/a.py"],
    )
    def test_exclusion_does_not_spread(self, push_config: RemoteConfig, rel_path: str) -> None:
        """SPEC_01/SPEC_02: 直下だけの除外・ルートの直下の設定ファイルの除外が，下に広がらない."""
        assert is_pushed(push_config, rel_path)


_BAD_REL_PATHS = [
    "",
    "/x",
    "C:/x",
    "C:x",
    "../x",
    "a/../b",
    "..",
    "./a",
    ".",
    "a//b",
    "a/",
    "data\\x",
    "data/x\x00.png",
]


class TestRelPathValidation:
    """SPEC_01: `rel_path` の書き方の誤りは `ValueError` にする."""

    @pytest.mark.parametrize("rel_path", _BAD_REL_PATHS)
    def test_is_pushed_rejects(self, push_config: RemoteConfig, rel_path: str) -> None:
        """SPEC_01: 空・絶対パス・`..`・`.`・空の部分・`\\`・NUL を含むと `ValueError`（push）."""
        with pytest.raises(ValueError):
            is_pushed(push_config, rel_path)
        with pytest.raises(ValueError):
            is_pushed(push_config, rel_path, is_dir=True)

    @pytest.mark.parametrize("rel_path", _BAD_REL_PATHS)
    def test_is_pulled_rejects(self, push_config: RemoteConfig, rel_path: str) -> None:
        """SPEC_01: 空・絶対パス・`..`・`.`・空の部分・`\\`・NUL を含むと `ValueError`（pull）."""
        with pytest.raises(ValueError):
            is_pulled(push_config, rel_path)
        with pytest.raises(ValueError):
            is_pulled(push_config, rel_path, with_checkpoints=True)

    @pytest.mark.parametrize("rel_path", ["src/model.py", "a.b/c", "..a/b", "a../b"])
    def test_normal_paths_are_accepted(self, push_config: RemoteConfig, rel_path: str) -> None:
        """SPEC_01: `/` 区切りの相対パスは受け付ける（`..` を含む名前は部分でなければよい）."""
        assert isinstance(is_pushed(push_config, rel_path), bool)
        assert isinstance(is_pulled(push_config, rel_path), bool)

    @pytest.mark.parametrize("value", [None, Path("src/model.py"), 1])
    def test_non_string_is_error(self, push_config: RemoteConfig, value: object) -> None:
        """仕様に無い: 文字列でない値はエラーになる（黙って判定しない）."""
        with pytest.raises((ValueError, TypeError)):
            is_pushed(push_config, value)  # type: ignore[arg-type]
        with pytest.raises((ValueError, TypeError)):
            is_pulled(push_config, value)  # type: ignore[arg-type]


class TestLoadConfig:
    """SPEC_01: `load_config(root)` は `<root>/labremote.yaml` を読む．親のフォルダは探さない."""

    @pytest.mark.parametrize("as_str", [False, True])
    def test_reads_root_config(self, tmp_path: Path, as_str: bool) -> None:
        """SPEC_01: `<root>/labremote.yaml` を読んで検証済みの設定を返す（root は Path・str）."""
        _write_config(tmp_path, _PUSH_YAML)
        config = load_config(str(tmp_path) if as_str else tmp_path)
        assert isinstance(config, RemoteConfig)
        assert config.project.name == "Sample"
        assert tuple(config.push.exclude_root) == ("data", "legacy")

    def test_does_not_search_parent(self, tmp_path: Path) -> None:
        """SPEC_01: 親のフォルダは探さない（親にあっても root に無ければエラー）."""
        _write_config(tmp_path, "push: {}\n")
        child = tmp_path / "child"
        child.mkdir()
        with pytest.raises(ValueError):
            load_config(child)

    def test_missing_file_is_error(self, tmp_path: Path) -> None:
        """SPEC_01: 設定ファイルが無ければエラー."""
        with pytest.raises(ValueError):
            load_config(tmp_path)

    def test_folder_with_config_name_is_error(self, tmp_path: Path) -> None:
        """SPEC_01: `labremote.yaml` という名前のフォルダは設定ファイルとみなさない."""
        (tmp_path / "labremote.yaml").mkdir()
        with pytest.raises(ValueError):
            load_config(tmp_path)

    def test_config_without_push_is_error(self, tmp_path: Path) -> None:
        """SPEC_02: `push` の節は省略できない（検証を通らない設定で，テストが黙って通らない）."""
        _write_config(tmp_path)
        with pytest.raises(ValidationError):
            load_config(tmp_path)

    def test_unknown_key_is_error(self, tmp_path: Path) -> None:
        """SPEC_02: 未知のキーは拒否する（`load_config` も同じ検証を通す）."""
        _write_config(tmp_path, "push:\n  exclude_rot: [data]\n")
        with pytest.raises(ValidationError):
            load_config(tmp_path)


def _fail(*_args: object, **_kwargs: object) -> None:
    raise AssertionError("ファイルシステム・subprocess を見てはならない")


class TestDoesNotTouchFiles:
    """SPEC_01: 手元のファイルを一覧しない・サーバに接続しない．渡した名前についてだけ答える."""

    _CASES = [
        ("data", True),
        ("data/train/a.png", False),
        ("src/model.py", False),
        ("src", True),
        ("runs/exp1/metrics.json", False),
    ]
    _PULLS = ["config.yaml", "images/a.png", "checkpoints/best.pth", "figures/loss.png"]

    def _answers(self, config: RemoteConfig) -> tuple[list[bool], list[bool]]:
        pushed = [is_pushed(config, rel, is_dir=is_dir) for rel, is_dir in self._CASES]
        pulled = [
            is_pulled(config, rel, with_checkpoints=flag)
            for rel in self._PULLS
            for flag in (False, True)
        ]
        return pushed, pulled

    def test_same_answers_after_project_is_removed(self, tmp_path: Path) -> None:
        """SPEC_01: 設定のオブジェクトだけで答える（読んだ後にプロジェクトを消しても同じ答え）."""
        root = tmp_path / "proj"
        _write_config(root, _PUSH_YAML, SAMPLE_RESULTS_YAML)
        (root / "src").mkdir()
        (root / "src" / "model.py").write_text("x", encoding="utf-8")
        config = load_config(root)
        before = self._answers(config)
        shutil.rmtree(root)
        assert self._answers(config) == before

    def test_does_not_call_filesystem_or_subprocess(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_01: 判定の実行中に，ファイルシステムを見る関数と subprocess が呼ばれない."""
        _write_config(tmp_path, _PUSH_YAML, SAMPLE_RESULTS_YAML)
        config = load_config(tmp_path)
        expected = self._answers(config)
        with monkeypatch.context() as m:
            for name in ("scandir", "listdir", "stat", "lstat", "walk"):
                m.setattr(os, name, _fail)
            for name in ("iterdir", "exists", "stat", "lstat", "resolve", "is_file", "is_dir"):
                m.setattr(Path, name, _fail)
            for name in ("run", "Popen", "call", "check_output"):
                m.setattr(subprocess, name, _fail)
            got = self._answers(config)
        assert got == expected


def test_public_api_is_only_three_functions() -> None:
    """SPEC_01: 公開の入口は `load_config`・`is_pushed`・`is_pulled` の 3 つだけ."""
    assert sorted(testing_module.__all__) == ["is_pulled", "is_pushed", "load_config"]
    public = sorted(
        name
        for name, value in vars(testing_module).items()
        if not name.startswith("_")
        and callable(value)
        and getattr(value, "__module__", None) == testing_module.__name__
    )
    assert public == ["is_pulled", "is_pushed", "load_config"]


# SPEC_02 の冒頭の例（TongueSegModel を想定）．例と実装の食い違いを見つけるため，文書から読む
_SPEC02_PATH = (
    Path(__file__).resolve().parents[1] / "docs" / "04_SPEC" / "SPEC_02_設定ファイル仕様.md"
)
_SPEC02_EXAMPLE_RE = re.compile(r"## 例 \(Example\).*?```yaml\n(.*?)```", re.DOTALL)


def _spec02_example() -> str:
    match = _SPEC02_EXAMPLE_RE.search(_SPEC02_PATH.read_text(encoding="utf-8"))
    assert match, "SPEC_02 の冒頭に yaml の例が無い"
    return match.group(1)


class TestSpecExample:
    """SPEC_01「プロジェクトの側のテスト」の例が，SPEC_02 の冒頭の例の設定でそのまま動く."""

    @pytest.fixture
    def config(self, tmp_path: Path) -> RemoteConfig:
        example = _spec02_example()
        # 前提: 例が YAML として正しく，push・results・run を含む
        raw = yaml.safe_load(example)
        assert {"push", "results", "run"} <= set(raw)
        (tmp_path / "labremote.yaml").write_text(example, encoding="utf-8")
        return load_config(tmp_path)

    @pytest.mark.parametrize("name", ["data", "legacy", "runs", ".claude"])
    def test_folders_that_must_not_be_sent(self, config: RemoteConfig, name: str) -> None:
        """SPEC_01 の例: `data`・`legacy`・`runs`・`.claude` は送られない."""
        assert not is_pushed(config, name, is_dir=True)

    @pytest.mark.parametrize("name", ["src", "external/TIASDataHub/src", "README.md"])
    def test_code_is_sent(self, config: RemoteConfig, name: str) -> None:
        """SPEC_01 の例の前提: 送るべきコードは送られる（全部を拒否して通るのではない）."""
        assert is_pushed(config, name, is_dir=not name.endswith(".md"))

    @pytest.mark.parametrize("name", ["images/a.png", "manifest.csv", "checkpoints/best.pth"])
    def test_names_that_must_not_be_pulled(self, config: RemoteConfig, name: str) -> None:
        """SPEC_01 の例: `images/a.png`・`manifest.csv`・`checkpoints/best.pth` は回収されない."""
        assert not is_pulled(config, name)

    @pytest.mark.parametrize("name", ["config.yaml", "figures/loss.png"])
    def test_names_that_are_pulled(self, config: RemoteConfig, name: str) -> None:
        """SPEC_02 の例: 一覧の名前（`config.yaml`・`figures/loss.png`）は回収される."""
        assert is_pulled(config, name)

    def test_checkpoint_pulled_only_with_flag(self, config: RemoteConfig) -> None:
        """SPEC_01/SPEC_02: 重みは `with_checkpoints=True` のときだけ回収される."""
        assert not is_pulled(config, "checkpoints/best.pth")
        assert is_pulled(config, "checkpoints/best.pth", with_checkpoints=True)
