"""このリポジトリの LabRemote の設定（`labremote.yaml`）のテスト（Issue #15 の 3-3）.

LabRemote の SPEC_01「プロジェクトの側のテスト」に従い，`labremote.testing` の
`load_config`・`is_pushed`・`is_pulled` で次を確かめる．

- 送ってはならないもの（`data/`・`legacy/`・結果の置き場・重み・`.env` 等）が `push` で
  送られないこと
- 回収してはならない名前（画像・manifest・指定の無い重み等）が `pull` で回収されないこと．
  重みは `--with-checkpoints` のときだけ回収されること
- 設定の `project.git_commit_env` と，学習側のコードが読む環境変数の名前が同じであること

`is_pushed` は実際のフォルダの中を見ない．ここでも「送られるファイルの一覧」は作らない
（データのフォルダの中身をテストの出力に出さないため）．名前はすべてテストに書いた架空のもの．

LabRemote の `tests/` に残っていた，このリポジトリに頼るテスト 17 件（スキップされていたもの）の
内容も移した（`test_config.py` の 2 件・`test_whitelist.py` の 14 件・`test_cli.py` の 1 件）．

サーバでは依存グループ `remote`（LabRemote）が入らず，`labremote.yaml` も送られないため，
どちらかが無ければモジュールごとスキップする．
"""

from __future__ import annotations

import re
from datetime import datetime
from pathlib import Path

import pytest

pytest.importorskip("labremote")

REPO_ROOT = Path(__file__).resolve().parents[1]
CONFIG_PATH = REPO_ROOT / "labremote.yaml"
if not CONFIG_PATH.is_file():
    pytest.skip("labremote.yaml が無い（サーバ上ではスキップする）", allow_module_level=True)

import yaml  # noqa: E402
from labremote.commands import build_job_env, format_git_commit  # noqa: E402
from labremote.testing import is_pulled, is_pushed, load_config  # noqa: E402
from labremote.whitelist import plan_pull, validate_run_id  # noqa: E402

from tongue_seg_model.training.run_artifacts import (  # noqa: E402
    CHECKPOINTS_DIRNAME,
    CONFIG_FILENAME,
    FIGURES_DIRNAME,
    GIT_COMMIT_ENV_VAR,
    LOG_FILENAME,
    make_run_id,
    resolve_git_commit,
)

CONFIG = load_config(REPO_ROOT)

RUN_ID = "20261119-120000_resunet_abc1234"

# ---------------------------------------------------------------------------
# 設定の読み込み（LabRemote の test_config.py の 2 件を移したもの）
# ---------------------------------------------------------------------------


def test_repository_labremote_yaml_loads() -> None:
    """移す元: LabRemote `tests/test_config.py::test_repository_remote_yaml_loads`."""
    assert CONFIG.project.name == "TongueSegModel"
    assert [s.name for s in CONFIG.ordered_servers()] == ["Newton", "Archimedes"]
    assert CONFIG.jump_host == "labpc"
    for server in CONFIG.servers:
        assert server.remote_dir == "~/work/TongueSegModel"
        assert server.uv == "~/.local/bin/uv"


def test_repository_labremote_yaml_has_no_address_user_or_key() -> None:
    """アドレス・ユーザー名・鍵の場所はリポジトリに書かない（手元の ~/.ssh/config から決める）.

    移す元: LabRemote `tests/test_config.py::
    test_repository_remote_yaml_has_no_address_user_or_key`．
    LabRemote の設定には `address`・`user` の項目自体が無いため，生の YAML とその本文で確かめる．
    """
    text = CONFIG_PATH.read_text(encoding="utf-8")
    raw = yaml.safe_load(text)
    for server in raw["servers"]:
        assert "address" not in server
        assert "user" not in server
    # コメントを含めて，IPv4 アドレス・鍵の場所・ユーザー名・アドレスの指定が無いこと
    assert not re.search(r"\b\d{1,3}(\.\d{1,3}){3}\b", text)
    assert not re.search(r"(?i)identityfile|id_rsa|id_ed25519|id_ecdsa|\.pem\b", text)
    assert not re.search(r"(?m)^\s*(-\s*)?(user|address|hostname)\s*:", text)


def test_server_dependency_group_is_excluded_on_server() -> None:
    """サーバの `uv run` で LabRemote（依存グループ remote）を入れない（LabRemote の SPEC_01）."""
    assert "remote" in CONFIG.run.exclude_groups


def test_results_dir_is_training_output_dir() -> None:
    """結果の置き場が，学習の出力先の既定（`run.out_dir`）と同じであること."""
    from tongue_seg_model.schema import RunConfig

    assert Path(CONFIG.results.dir) == RunConfig().out_dir


# ---------------------------------------------------------------------------
# 送信（push）
# ---------------------------------------------------------------------------

# 送ってはならないフォルダ（ルートの直下）
NOT_SENT_DIRS = [
    "data",
    "legacy",
    "runs",
    "runs/_remote_logs",
    ".claude",
    ".git",
    ".venv",
    "__pycache__",
    ".pytest_cache",
    ".ruff_cache",
    "src/tongue_seg_model/__pycache__",
    # 大文字小文字を問わない（Windows では同じフォルダ）
    "Data",
    "LEGACY",
    "Runs",
    # サブモジュール TIASDataHub のうち，導入に要らないもの
    "external/TIASDataHub/docs",
    "external/TIASDataHub/tests",
    "external/TIASDataHub/.claude",
    "external/TIASDataHub/datasets",
]

# 送ってはならないファイル（名前はすべて架空）
NOT_SENT_FILES = [
    # データ・原本・結果の置き場の中（途中のフォルダが除外されていれば送られない）
    "data/synthetic/manifest.csv",
    "data/synthetic/synthetic/v1/files/ab.png",
    "data/x/y/z.txt",
    "legacy/source/main.py",
    "legacy/hparams.yaml",
    "legacy/result/x.csv",
    "legacy/output/bestModel.pth",
    "Legacy/source/main.py",
    "DATA/x.png",
    "runs/20261119-120000_x/metrics.json",
    "runs/20261119-120000_x/predictions.csv",
    "runs/_remote_logs/exp1.log",
    # この設定ファイル自体
    "labremote.yaml",
    # 重み（どの階層でも・大文字小文字を問わず）
    "model.pt",
    "best.pth",
    "src/tongue_seg_model/models/best.pth",
    "tests/fixtures/ResUNet.onnx",
    "scripts/x.ckpt",
    "configs/frozen.pb",
    "BEST.PTH",
    "a/b/c/Model.Onnx",
    "x.tar.pt",
    "external/TIASDataHub/src/tiasdata/w.pth",
    # 環境変数ファイル（秘密を含みうる）
    ".env",
    ".env.local",
    "configs/.env",
    "src/.ENV",
    ".Env.production",
    # 手元の設定・キャッシュ・履歴
    ".claude/settings.json",
    ".claude/rules/testing.md",
    ".git/config",
    ".venv/Scripts/python.exe",
    "src/tongue_seg_model/__pycache__/a.cpython-312.pyc",
    "tests/data/__pycache__/b.pyc",
    # サブモジュール TIASDataHub のうち，導入に要らないもの
    "external/TIASDataHub/.git",
    "external/TIASDataHub/CLAUDE.md",
    "external/TIASDataHub/uv.lock",
    "external/TIASDataHub/docs/PROGRESS.md",
    "external/TIASDataHub/tests/test_bundle.py",
    "external/TIASDataHub/datasets/tongue_color.toml",
    "external/TIASDataHub/src/tiasdata/__pycache__/bundle.cpython-312.pyc",
]

# サーバで学習するのに要るもの（送られなければならない）
SENT_FILES = [
    "pyproject.toml",
    "uv.lock",
    ".python-version",
    "configs/resunet.yaml",
    "configs/synthetic.yaml",
    "configs/synthetic-gpu.yaml",
    "scripts/make_synthetic_bundle.py",
    "src/tongue_seg_model/__init__.py",
    "src/tongue_seg_model/data/bundle.py",
    "src/tongue_seg_model/training/run_artifacts.py",
    "src/tongue_seg_model/export/onnx_export.py",
    "tests/data/test_split.py",
    # 重みの拡張子・.env・data・legacy・runs に似ているが違うもの
    "docs/onnx.md",
    "scripts/pth_tool.py",
    "src/a.pth.py",
    ".envrc",
    "my.env",
    "src/environment.py",
    "legacy.md",
    "docs/legacy/a.md",
    "tests/runs/a.py",
    "src/tongue_seg_model/runs_util.py",
    # サブモジュール TIASDataHub は導入に要るものだけ
    "external/TIASDataHub/pyproject.toml",
    "external/TIASDataHub/README.md",
    "external/TIASDataHub/src/tiasdata/__init__.py",
    "external/TIASDataHub/src/tiasdata/catalog/migrations/catalog/0001_x.sql",
]

# 送られなければならないフォルダ（パッケージの data・テストの data は直下の data とは別）
SENT_DIRS = [
    "src",
    "src/tongue_seg_model/data",
    "tests/data",
    "configs",
    "scripts",
    "external",
    "external/TIASDataHub",
    "external/TIASDataHub/src",
]


@pytest.mark.parametrize("rel", NOT_SENT_DIRS)
def test_directories_that_must_not_be_sent(rel: str) -> None:
    assert not is_pushed(CONFIG, rel, is_dir=True)


@pytest.mark.parametrize("rel", NOT_SENT_FILES)
def test_files_that_must_not_be_sent(rel: str) -> None:
    assert not is_pushed(CONFIG, rel)


@pytest.mark.parametrize("rel", SENT_FILES)
def test_files_needed_on_server_are_sent(rel: str) -> None:
    assert is_pushed(CONFIG, rel)


@pytest.mark.parametrize("rel", SENT_DIRS)
def test_directories_needed_on_server_are_sent(rel: str) -> None:
    assert is_pushed(CONFIG, rel, is_dir=True)


@pytest.mark.parametrize("rel", ["models.onnx", "src/weights.pth", ".env.d"])
def test_file_rules_do_not_apply_to_directories(rel: str) -> None:
    """重みの拡張子・`.env` の除外はファイルにだけかかる（フォルダの中は名前で判断する）."""
    assert is_pushed(CONFIG, rel, is_dir=True)
    assert not is_pushed(CONFIG, f"{rel}/w.pth")


@pytest.mark.parametrize("suffix", [".pt", ".pth", ".ckpt", ".pb", ".onnx"])
def test_every_weight_suffix_is_excluded(suffix: str) -> None:
    """`.gitignore` の重みの拡張子がすべて送られない（設定の `push.exclude_suffixes`）."""
    assert not is_pushed(CONFIG, f"src/w{suffix}")
    assert not is_pushed(CONFIG, f"src/W{suffix.upper()}")


# ---------------------------------------------------------------------------
# 回収（pull）
# ---------------------------------------------------------------------------

PULLED = [
    "config.yaml",
    "history.csv",
    "metrics.json",
    "log.txt",
    # 画像ごとの結果・分割結果は回収する（Issue #15 の 3-1 で足した．実験を消す前に回収するため）
    "predictions.csv",
    "split.json",
    "figures/loss.png",
    "figures/iou.png",
    "figures/a b.png",
]

CHECKPOINTS = ["checkpoints/best.pth", "checkpoints/ResUNet.onnx"]

# 回収してはならない（--with-checkpoints を付けても回収しない）．名前はすべて架空
NOT_PULLED = [
    "manifest.csv",
    "data/manifest.csv",
    "per_image_predictions.csv",
    # 画像（figures/ 以外の png・figures/ の png 以外・figures/ の下の階層）
    "a.png",
    "loss.png",
    "P0001_tongue.png",
    "P0001_tongue.jpg",
    "images/P0001.png",
    "masks/P0001.png",
    "predictions/P0001.png",
    "figures/x.jpg",
    "figures/x.bmp",
    "figures/x.npy",
    "figures/sub/a.png",
    "sub/figures/a.png",
    "figures/config.yaml",
    # 名前の似たもの・下の階層
    "config.yml",
    "config.yaml.bak",
    ".config.yaml",
    "metrics.json.tmp",
    "log.txt.1",
    "sub/config.yaml",
    "checkpoints/config.yaml",
    "split.json.bak",
    "sub/predictions.csv",
    # 大文字小文字の違い（完全一致で比べる）
    "Config.yaml",
    "METRICS.JSON",
    "Predictions.csv",
    "SPLIT.JSON",
    "figures/loss.PNG",
    "Figures/loss.png",
    # Windows が末尾の . や空白を捨てて別の名前になるもの・代替データストリーム・制御文字
    "config.yaml.",
    "config.yaml ",
    "figures/a.png.",
    "config.yaml:secret",
    "figures/a:b.png",
    "figures/a?b.png",
    "config.yaml\n",
    "figures/a\r.png",
    # 重み（指定の無いもの・名前が完全一致しないもの・置き場が違うもの）
    "checkpoints/epoch3.pth",
    "checkpoints/last.pth",
    "checkpoints/resunet.onnx",
    "checkpoints/Best.pth",
    "checkpoints/best.pt",
    "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",
]


@pytest.mark.parametrize("with_checkpoints", [False, True])
@pytest.mark.parametrize("rel", PULLED)
def test_listed_results_are_pulled(rel: str, with_checkpoints: bool) -> None:
    assert is_pulled(CONFIG, rel, with_checkpoints=with_checkpoints)


@pytest.mark.parametrize("with_checkpoints", [False, True])
@pytest.mark.parametrize("rel", NOT_PULLED)
def test_names_that_must_not_be_pulled(rel: str, with_checkpoints: bool) -> None:
    assert not is_pulled(CONFIG, rel, with_checkpoints=with_checkpoints)


@pytest.mark.parametrize("rel", CHECKPOINTS)
def test_checkpoints_are_pulled_only_with_checkpoints(rel: str) -> None:
    assert not is_pulled(CONFIG, rel)
    assert is_pulled(CONFIG, rel, with_checkpoints=True)


@pytest.mark.parametrize(
    "rel", ["../config.yaml", "./config.yaml", "figures//a.png", "/config.yaml", "figures\\a.png"]
)
def test_malformed_paths_are_rejected(rel: str) -> None:
    """意図が曖昧なパスは「回収されない」と答えずに ValueError にする（LabRemote の SPEC_01）."""
    with pytest.raises(ValueError):
        is_pulled(CONFIG, rel)


def test_pull_names_match_files_written_by_training() -> None:
    """学習が書く名前が回収の一覧と一致すること（どちらかの名前を変えたら気づくため）."""
    from tongue_seg_model.data.split import SPLIT_FILENAME
    from tongue_seg_model.export.onnx_export import ONNX_FILENAME
    from tongue_seg_model.training.experiment import BEST_CHECKPOINT_FILENAME
    from tongue_seg_model.training.history import HISTORY_FILENAME, LOSS_FIGURE_FILENAME
    from tongue_seg_model.training.metrics import METRICS_FILENAME, PREDICTIONS_FILENAME

    for name in [
        CONFIG_FILENAME,
        LOG_FILENAME,
        HISTORY_FILENAME,
        METRICS_FILENAME,
        PREDICTIONS_FILENAME,
        SPLIT_FILENAME,
        f"{FIGURES_DIRNAME}/{LOSS_FIGURE_FILENAME}",
    ]:
        assert is_pulled(CONFIG, name), name
    for name in [BEST_CHECKPOINT_FILENAME, ONNX_FILENAME]:
        rel = f"{CHECKPOINTS_DIRNAME}/{name}"
        assert not is_pulled(CONFIG, rel), rel
        assert is_pulled(CONFIG, rel, with_checkpoints=True), rel


# ---------------------------------------------------------------------------
# 実験 ID（LabRemote の test_whitelist.py の 12 件・test_cli.py の 1 件を移したもの）
# ---------------------------------------------------------------------------


@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(config_name: str, git_commit: str) -> None:
    """移す元: LabRemote `test_whitelist.py` の `TestRunIdOfProjectMakeRunId` の同名のテスト."""
    run_id = make_run_id(datetime(2026, 11, 19, 12, 0, 0), config_name, git_commit)
    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(config_name: str) -> None:
    """設定ファイル名が Windows の予約名でも，実験 ID 全体は予約名にならない（日時で始まる）.

    移す元: LabRemote `test_whitelist.py` の同名のテスト．
    """
    run_id = make_run_id(datetime(2026, 11, 19, 12, 0, 0), config_name, "abc1234-dirty")
    assert validate_run_id(run_id) == run_id


def test_make_run_id_is_accepted_by_pull_plan() -> None:
    """`make_run_id` の実験 ID（-dirty 付き）で，pull が一覧に一致するものだけを選ぶ.

    移す元: LabRemote `test_cli.py::TestPull::test_make_run_id_is_accepted_by_pull`．
    元は LabRemote のテスト用の ssh のモックで `cli.main(["pull", ...])` を通していたが，
    ここでは pull が使う公開の判定（`validate_run_id`・`plan_pull`）をこの設定で呼ぶ．
    """
    run_id = make_run_id(datetime(2026, 11, 19, 1, 2, 3), "synthetic-gpu", "abc1234-dirty")
    assert validate_run_id(run_id) == run_id
    listing = [
        ("f", f"{run_id}/config.yaml"),
        ("f", f"{run_id}/manifest.csv"),
        ("f", f"{run_id}/images/P0001.png"),
        ("f", f"{run_id}/checkpoints/best.pth"),
        # 名前が一致してもリンク等の通常ファイル以外は回収しない
        ("l", f"{run_id}/metrics.json"),
        ("d", f"{run_id}/figures"),
    ]
    plan = plan_pull(listing, run_id, CONFIG.results, with_checkpoints=False)
    assert plan.files == (f"{run_id}/config.yaml",)
    assert plan.skipped_checkpoints == 1

    plan = plan_pull(listing, run_id, CONFIG.results, with_checkpoints=True)
    assert sorted(plan.files) == sorted([f"{run_id}/config.yaml", f"{run_id}/checkpoints/best.pth"])


# ---------------------------------------------------------------------------
# git のハッシュの受け渡し（LabRemote の test_whitelist.py の 2 件を移したもの）
# ---------------------------------------------------------------------------


def test_git_commit_env_var_is_the_same_in_config_and_training() -> None:
    """設定の `git_commit_env` と，学習側のコードが読む環境変数の名前が同じであること.

    移す元: LabRemote `test_whitelist.py::
    test_git_commit_env_var_is_the_same_in_remote_and_training`．
    元は `LABREMOTE_GIT_COMMIT` 決め打ちだったが，LabRemote は設定の名前でも同じ値を渡すため，
    設定の値と比べる．
    """
    assert CONFIG.project.git_commit_env == GIT_COMMIT_ENV_VAR


@pytest.mark.parametrize(
    "short_hash", ["abc1", "abc1234", "0123456789abcdef0123456789abcdef01234567"]
)
@pytest.mark.parametrize("dirty", [False, True])
def test_value_passed_by_labremote_is_accepted_by_training(short_hash: str, dirty: bool) -> None:
    """LabRemote がジョブに渡す環境変数から，学習側が同じ値を受け取り，実験 ID にできること.

    移す元: LabRemote `test_whitelist.py::TestRunIdOfProjectMakeRunId::
    test_value_passed_by_remote_is_accepted_by_training`．元は `LABREMOTE_GIT_COMMIT` に直接
    入れていたが，ここでは `build_job_env` にこの設定の `git_commit_env` を渡して組み立てる．
    """
    value = format_git_commit(short_hash, dirty=dirty)
    assert value is not None
    env = build_job_env(0, [], git_commit=value, git_commit_env=CONFIG.project.git_commit_env)
    assert resolve_git_commit(env) == value
    run_id = make_run_id(datetime(2026, 1, 2, 3, 4, 5), "resunet", value)
    assert validate_run_id(run_id) == run_id
