"""`tsm-train --config PATH`（`cli/train.py`）の統合テスト.

期待値は SPEC_01「CLI」（設定に従って学習し，最後に実験 ID を出力する）と，CLI の終了コード
（0: 成功・1: 設定・環境・バンドル・データの問題でスタックトレースを出さない・2: 引数の誤り）を
基準にする．`main` は `bundles_dir` を受け取らないので，バンドルの置き場所は環境変数
`TIASDATA_BUNDLES` を monkeypatch で `tmp_path` に向ける（テスト後に元に戻る）．
"""

from __future__ import annotations

import importlib.metadata
import logging
import re
from collections.abc import Iterator
from pathlib import Path
from typing import Any

import pytest
import yaml

from tongue_seg_model.cli.train import main
from tongue_seg_model.data.synthetic import write_synthetic_bundle
from tongue_seg_model.training.run_artifacts import GIT_COMMIT_ENV_VAR, configure_logging

SIZE = (64, 64)
BUNDLES_ENV_VAR = "TIASDATA_BUNDLES"
RUN_ID_RE = re.compile(r"^\d{8}-\d{6}_tiny_abc1234$")


@pytest.fixture(autouse=True)
def restore_logging() -> Iterator[None]:
    """root logger の状態を戻し，`log.txt` のハンドラを閉じる（Windows での削除失敗を防ぐ）."""
    root = logging.getLogger()
    level = root.level
    yield
    configure_logging(None)
    for handler in list(root.handlers):
        if handler.get_name() and handler.get_name().startswith("tongue_seg_model."):
            root.removeHandler(handler)
            handler.close()
    root.setLevel(level)


@pytest.fixture
def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
    """バンドルの置き場所と git のハッシュを tmp_path 向けに設定し，置き場所を返す."""
    bundles = tmp_path / "bundles"
    bundles.mkdir()
    monkeypatch.setenv(BUNDLES_ENV_VAR, str(bundles))
    monkeypatch.setenv(GIT_COMMIT_ENV_VAR, "abc1234")
    return bundles


def _write_config(tmp_path: Path, **overrides: Any) -> Path:
    raw: dict[str, Any] = {
        "data": {"bundle": {"name": "synthetic", "version": 1}, "image_size": list(SIZE)},
        "model": {"pretrained": False},
        "train": {"batch_size": 2, "max_epochs": 1, "device": "cpu", "seed": 0},
        "run": {"out_dir": str(tmp_path / "runs")},
    }
    for section, values in overrides.items():
        raw.setdefault(section, {}).update(values)
    path = tmp_path / "tiny.yaml"
    path.write_text(yaml.safe_dump(raw), encoding="utf-8")
    return path


def test_entry_point_is_registered() -> None:
    points = importlib.metadata.entry_points(group="console_scripts", name="tsm-train")
    assert [p.value for p in points] == ["tongue_seg_model.cli.train:main"]


class TestArgumentErrors:
    def test_missing_config_option_exits_with_2(self) -> None:
        with pytest.raises(SystemExit) as info:
            main([])
        assert info.value.code == 2

    def test_unknown_option_exits_with_2(self, tmp_path: Path) -> None:
        with pytest.raises(SystemExit) as info:
            main(["--config", str(tmp_path / "x.yaml"), "--epochs", "3"])
        assert info.value.code == 2


class TestInputErrors:
    def _assert_clean_failure(self, capsys: pytest.CaptureFixture[str]) -> str:
        captured = capsys.readouterr()
        assert captured.out == ""
        assert "Traceback" not in captured.err
        assert "学習を中止した" in captured.err
        return captured.err

    def test_missing_config_file(
        self, tmp_path: Path, env: Path, capsys: pytest.CaptureFixture[str]
    ) -> None:
        assert main(["--config", str(tmp_path / "missing.yaml")]) == 1
        self._assert_clean_failure(capsys)

    def test_unknown_key_in_config(
        self, tmp_path: Path, env: Path, capsys: pytest.CaptureFixture[str]
    ) -> None:
        path = _write_config(tmp_path, train={"unknown_key": 1})
        assert main(["--config", str(path)]) == 1
        self._assert_clean_failure(capsys)
        assert not (tmp_path / "runs").exists()

    def test_image_size_not_multiple_of_32_creates_nothing(
        self, tmp_path: Path, env: Path, capsys: pytest.CaptureFixture[str]
    ) -> None:
        path = _write_config(tmp_path, data={"image_size": [48, 48]})
        assert main(["--config", str(path)]) == 1
        self._assert_clean_failure(capsys)
        runs = tmp_path / "runs"
        assert not runs.exists() or not any(runs.iterdir())

    def test_missing_bundle_keeps_run_dir_and_logs_reason(
        self, tmp_path: Path, env: Path, capsys: pytest.CaptureFixture[str]
    ) -> None:
        path = _write_config(tmp_path)
        assert main(["--config", str(path)]) == 1
        self._assert_clean_failure(capsys)
        run_dirs = list((tmp_path / "runs").iterdir())
        assert len(run_dirs) == 1
        assert RUN_ID_RE.match(run_dirs[0].name)
        for handler in logging.getLogger().handlers:
            handler.flush()
        log = (run_dirs[0] / "log.txt").read_text(encoding="utf-8")
        assert "学習を中止した" in log
        assert "Traceback" not in log
        assert not (run_dirs[0] / "metrics.json").exists()


@pytest.mark.slow
def test_successful_run_prints_only_run_id(
    tmp_path: Path, env: Path, capsys: pytest.CaptureFixture[str]
) -> None:
    write_synthetic_bundle(env, train_pairs=6, test_pairs=2, seed=0, image_size=SIZE)
    path = _write_config(tmp_path)
    assert main(["--config", str(path)]) == 0
    captured = capsys.readouterr()
    lines = captured.out.split("\n")
    assert len(lines) == 2 and lines[1] == ""
    run_id = lines[0]
    assert RUN_ID_RE.match(run_id)
    run_dir = tmp_path / "runs" / run_id
    for name in ("config.yaml", "history.csv", "metrics.json", "log.txt", "predictions.csv"):
        assert (run_dir / name).is_file()
    assert (run_dir / "checkpoints" / "best.pth").is_file()
    assert (run_dir / "figures" / "loss.png").is_file()
    # ログは標準エラーに出る（標準出力は実験 ID だけ）
    assert run_id in captured.err
