"""1 回の実験を通す `run_training`（`training/experiment.py`）のテスト.

期待値は SPEC_01「実験の出力」（`runs/<実験ID>/` のファイル構成・実験 ID の書式・同じ実験 ID の
フォルダがあれば止める・`figures/` には図だけ）・「回収ホワイトリスト」（回収するファイルに画像の
ファイル名・患者 ID が入らないこと）と SPEC_02「学習」「学習後の評価」を基準にする．

合成バンドルを `tmp_path` に作り，`bundles_dir`・`environ`・`now` を引数で渡す（環境変数を
書き換えない）．学習を回すテストは `slow`．
"""

from __future__ import annotations

import csv
import io
import json
import logging
import re
from collections.abc import Iterator
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any

import pytest
import torch
import yaml

from tongue_seg_model.data.synthetic import write_synthetic_bundle
from tongue_seg_model.models.resunet import ResUNet
from tongue_seg_model.schema import ExperimentConfig
from tongue_seg_model.training.experiment import run_training
from tongue_seg_model.training.run_artifacts import GIT_COMMIT_ENV_VAR, configure_logging

SIZE = (64, 64)
TRAIN_PAIRS = 6
TEST_PAIRS = 2
NOW = datetime(2026, 11, 19, 10, 20, 30)
COMMIT = "abc1234-dirty"
ENVIRON = {GIT_COMMIT_ENV_VAR: COMMIT}
RUN_ID = "20261119-102030_synthetic_abc1234-dirty"

# SPEC_01「実験の出力」のファイル構成（ONNX は書き出しを実行したときだけ）
EXPECTED_TOP_LEVEL = {
    "config.yaml",
    "history.csv",
    "metrics.json",
    "log.txt",
    "figures",
    "split.json",
    "predictions.csv",
    "checkpoints",
}
TEXT_OUTPUTS = (
    "config.yaml",
    "history.csv",
    "metrics.json",
    "log.txt",
    "split.json",
    "predictions.csv",
)


def _close_own_handlers() -> None:
    configure_logging(None)
    root = logging.getLogger()
    for handler in list(root.handlers):
        if handler.get_name() and handler.get_name().startswith("tongue_seg_model."):
            root.removeHandler(handler)
            handler.close()


@pytest.fixture
def restore_logging() -> Iterator[None]:
    """root logger の状態を戻し，`log.txt` のハンドラを閉じる（Windows での削除失敗を防ぐ）."""
    level = logging.getLogger().level
    yield
    _close_own_handlers()
    logging.getLogger().setLevel(level)


def _config(out_dir: Path, **overrides: Any) -> ExperimentConfig:
    raw: dict[str, Any] = {
        "data": {"bundle": {"name": "synthetic", "version": 1}, "image_size": list(SIZE)},
        "model": {"pretrained": False},
        "train": {
            "batch_size": 2,
            "max_epochs": 2,
            "early_stopping_patience": 5,
            "device": "cpu",
            "seed": 0,
        },
        "run": {"out_dir": str(out_dir)},
    }
    for section, values in overrides.items():
        raw.setdefault(section, {}).update(values)
    return ExperimentConfig.model_validate(raw)


def _write_bundle(bundles_dir: Path) -> Path:
    return write_synthetic_bundle(
        bundles_dir, train_pairs=TRAIN_PAIRS, test_pairs=TEST_PAIRS, seed=0, image_size=SIZE
    )


@dataclass(frozen=True)
class TrainedRun:
    outcome: Any
    bundle_dir: Path
    out_dir: Path


@pytest.fixture(scope="module")
def trained(tmp_path_factory: pytest.TempPathFactory) -> Iterator[TrainedRun]:
    """合成バンドルで 2 エポック回した実験（このモジュールの slow のテストで共有する）."""
    root = tmp_path_factory.mktemp("experiment")
    bundle_dir = _write_bundle(root / "bundles")
    out_dir = root / "runs"
    level = logging.getLogger().level
    try:
        outcome = run_training(
            _config(out_dir),
            config_name="synthetic",
            environ=ENVIRON,
            now=NOW,
            bundles_dir=root / "bundles",
        )
        yield TrainedRun(outcome=outcome, bundle_dir=bundle_dir, out_dir=out_dir)
    finally:
        _close_own_handlers()
        logging.getLogger().setLevel(level)


def _read_csv(path: Path) -> list[dict[str, str]]:
    return list(csv.DictReader(io.StringIO(path.read_text(encoding="utf-8"))))


def _strict_json(path: Path) -> Any:
    def _reject(constant: str) -> Any:
        raise AssertionError(f"厳密な JSON でない値 {constant} がある")

    return json.loads(path.read_text(encoding="utf-8"), parse_constant=_reject)


# ---------------------------------------------------------------------------
# 一通り回したときの出力
# ---------------------------------------------------------------------------


@pytest.mark.slow
class TestOutputs:
    def test_run_id_and_dir(self, trained: TrainedRun) -> None:
        assert trained.outcome.run_id == RUN_ID
        assert trained.outcome.run_dir == trained.out_dir / RUN_ID
        assert trained.outcome.run_dir.is_dir()

    def test_files_match_spec01(self, trained: TrainedRun) -> None:
        run_dir = trained.outcome.run_dir
        assert {p.name for p in run_dir.iterdir()} == EXPECTED_TOP_LEVEL

    def test_figures_contains_only_loss_png(self, trained: TrainedRun) -> None:
        figures = trained.outcome.run_dir / "figures"
        assert [p.name for p in figures.iterdir()] == ["loss.png"]
        assert (figures / "loss.png").read_bytes().startswith(b"\x89PNG\r\n\x1a\n")

    def test_no_png_outside_figures(self, trained: TrainedRun) -> None:
        run_dir = trained.outcome.run_dir
        pngs = [p.relative_to(run_dir).as_posix() for p in run_dir.rglob("*.png")]
        assert pngs == ["figures/loss.png"]

    def test_checkpoints_contains_only_best_pth(self, trained: TrainedRun) -> None:
        checkpoints = trained.outcome.run_dir / "checkpoints"
        assert [p.name for p in checkpoints.iterdir()] == ["best.pth"]

    def test_best_pth_loads_into_resunet(self, trained: TrainedRun) -> None:
        state = torch.load(trained.outcome.run_dir / "checkpoints" / "best.pth", weights_only=True)
        ResUNet(pretrained=False).load_state_dict(state)

    def test_history_csv(self, trained: TrainedRun) -> None:
        path = trained.outcome.run_dir / "history.csv"
        assert path.read_text(encoding="utf-8").split("\n")[0] == "epoch,train_loss,val_loss"
        rows = _read_csv(path)
        assert [int(r["epoch"]) for r in rows] == list(
            range(1, trained.outcome.metrics["epochs_run"] + 1)
        )
        for row in rows:
            float(row["train_loss"])
            float(row["val_loss"])

    def test_metrics_json(self, trained: TrainedRun) -> None:
        metrics = _strict_json(trained.outcome.run_dir / "metrics.json")
        assert metrics == trained.outcome.metrics
        assert set(metrics) == {
            "best_epoch",
            "best_val_loss",
            "epochs_run",
            "stopped_early",
            "test_iou",
            "counts",
            "data_bundle",
            "elapsed_seconds",
        }
        assert metrics["epochs_run"] == 2
        assert metrics["stopped_early"] is False
        assert 1 <= metrics["best_epoch"] <= metrics["epochs_run"]
        assert set(metrics["test_iou"]) == {"count", "mean", "median", "min", "max", "std"}
        assert metrics["test_iou"]["count"] == TEST_PAIRS
        for key in ("mean", "median", "min", "max"):
            assert 0.0 <= metrics["test_iou"][key] <= 1.0
        # 学習・検証は train_ratio（既定 2/3）で分ける
        assert metrics["counts"] == {"train": 4, "val": 2, "test": TEST_PAIRS}
        assert metrics["elapsed_seconds"] > 0

    def test_best_val_loss_matches_history(self, trained: TrainedRun) -> None:
        metrics = trained.outcome.metrics
        rows = _read_csv(trained.outcome.run_dir / "history.csv")
        val = [float(r["val_loss"]) for r in rows]
        assert metrics["best_val_loss"] == min(val)
        assert val.index(min(val)) + 1 == metrics["best_epoch"]

    def test_data_bundle_fingerprint_is_same_in_config_and_metrics(
        self, trained: TrainedRun
    ) -> None:
        run_dir = trained.outcome.run_dir
        config = yaml.safe_load((run_dir / "config.yaml").read_text(encoding="utf-8"))
        metrics = _strict_json(run_dir / "metrics.json")
        dataset = json.loads((trained.bundle_dir / "dataset.json").read_text(encoding="utf-8"))
        expected = {
            "name": "synthetic",
            "version": 1,
            "manifest_sha256": dataset["manifest_sha256"],
        }
        assert config["run"]["data_bundle"] == expected
        assert metrics["data_bundle"] == expected

    def test_config_yaml_run_section(self, trained: TrainedRun) -> None:
        run_dir = trained.outcome.run_dir
        config = yaml.safe_load((run_dir / "config.yaml").read_text(encoding="utf-8"))
        assert config["run"]["id"] == RUN_ID
        assert config["run"]["git_commit"] == COMMIT
        assert config["run"]["seed"] == 0
        assert ExperimentConfig.model_validate(config["config"]) == _config(trained.out_dir)

    def test_predictions_csv(self, trained: TrainedRun) -> None:
        path = trained.outcome.run_dir / "predictions.csv"
        assert path.read_text(encoding="utf-8").split("\n")[0] == "image_line,iou"
        rows = _read_csv(path)
        assert len(rows) == TEST_PAIRS
        lines = [int(r["image_line"]) for r in rows]
        assert len(set(lines)) == TEST_PAIRS
        assert all(line >= 2 for line in lines)  # manifest の行番号（見出しが 1 行目）
        split = _strict_json(trained.outcome.run_dir / "split.json")
        assert sorted(lines) == sorted(split["image_lines"]["test"])
        ious = [float(r["iou"]) for r in rows]
        assert all(0.0 <= v <= 1.0 for v in ious)
        metrics = trained.outcome.metrics["test_iou"]
        assert min(ious) == pytest.approx(metrics["min"])
        assert max(ious) == pytest.approx(metrics["max"])
        assert sum(ious) / len(ious) == pytest.approx(metrics["mean"])

    def test_log_txt_has_content(self, trained: TrainedRun) -> None:
        text = (trained.outcome.run_dir / "log.txt").read_text(encoding="utf-8")
        assert RUN_ID in text
        assert text.strip()


@pytest.mark.slow
class TestNoIdentifyingInformation:
    """出力のどこにもデータのファイル名・パス・患者 ID が入らない（testing.md の最重要項目）."""

    def _secrets(self, trained: TrainedRun) -> list[str]:
        files = [p for p in (trained.bundle_dir / "files").iterdir()]
        assert files, "合成バンドルにファイルがない"
        secrets = [p.stem for p in files] + [p.name for p in files]
        secrets += [str(trained.bundle_dir), trained.bundle_dir.as_posix()]
        secrets += [str(trained.bundle_dir.parent), trained.bundle_dir.parent.as_posix()]
        return secrets

    @pytest.mark.parametrize("name", TEXT_OUTPUTS)
    def test_no_file_names_or_data_paths(self, trained: TrainedRun, name: str) -> None:
        text = (trained.outcome.run_dir / name).read_text(encoding="utf-8")
        for secret in self._secrets(trained):
            assert secret not in text, f"{name} にデータのファイル名・パスがある"

    @pytest.mark.parametrize("name", TEXT_OUTPUTS)
    def test_no_subject_or_capture_ids(self, trained: TrainedRun, name: str) -> None:
        text = (trained.outcome.run_dir / name).read_text(encoding="utf-8")
        # 合成データの患者 ID・撮影 ID は syn-s0001・syn-c0001 の形
        assert not re.search(r"syn-[sc]\d{4}", text), f"{name} に患者 ID・撮影 ID がある"

    @pytest.mark.parametrize("name", TEXT_OUTPUTS)
    def test_no_hash_other_than_manifest(self, trained: TrainedRun, name: str) -> None:
        text = (trained.outcome.run_dir / name).read_text(encoding="utf-8")
        manifest = trained.outcome.metrics["data_bundle"]["manifest_sha256"]
        hashes = set(re.findall(r"[0-9a-f]{64}", text)) - {manifest}
        assert not hashes, f"{name} に manifest 以外のハッシュ（ファイル名）がある"


@pytest.mark.slow
@pytest.mark.usefixtures("restore_logging")
def test_same_config_reproduces_history_and_metrics(trained: TrainedRun) -> None:
    # 同じ設定・同じバンドルでもう一度回すと（実験 ID だけ違う）履歴と指標が一致する
    outcome = run_training(
        _config(trained.out_dir),
        config_name="synthetic",
        environ=ENVIRON,
        now=datetime(2026, 11, 19, 10, 20, 31),
        bundles_dir=trained.bundle_dir.parents[1],
    )
    first = trained.outcome
    assert outcome.run_id != first.run_id
    for name in ("history.csv", "predictions.csv", "split.json"):
        assert (outcome.run_dir / name).read_bytes() == (first.run_dir / name).read_bytes()
    a = {k: v for k, v in outcome.metrics.items() if k != "elapsed_seconds"}
    b = {k: v for k, v in first.metrics.items() if k != "elapsed_seconds"}
    assert a == b


@pytest.mark.slow
@pytest.mark.usefixtures("restore_logging")
def test_subject_split_runs(tmp_path: Path) -> None:
    _write_bundle(tmp_path / "bundles")
    outcome = run_training(
        _config(tmp_path / "runs", data={"split": "subject"}, train={"max_epochs": 1}),
        config_name="synthetic",
        environ={},
        now=NOW,
        bundles_dir=tmp_path / "bundles",
    )
    assert outcome.run_id == "20261119-102030_synthetic_nogit"
    split = _strict_json(outcome.run_dir / "split.json")
    assert split["method"] == "subject"
    assert outcome.metrics["epochs_run"] == 1


# ---------------------------------------------------------------------------
# 止まり方: フォルダを作る前に止まる
# ---------------------------------------------------------------------------


@pytest.mark.usefixtures("restore_logging")
class TestStopsBeforeCreatingRunDir:
    def _assert_nothing_created(self, out_dir: Path) -> None:
        assert not (out_dir / RUN_ID).exists()
        assert not out_dir.exists() or not any(out_dir.iterdir())

    def test_image_size_not_multiple_of_32(self, tmp_path: Path) -> None:
        _write_bundle(tmp_path / "bundles")
        out_dir = tmp_path / "runs"
        with pytest.raises(ValueError):
            run_training(
                _config(out_dir, data={"image_size": [48, 48]}),
                config_name="synthetic",
                environ=ENVIRON,
                now=NOW,
                bundles_dir=tmp_path / "bundles",
            )
        self._assert_nothing_created(out_dir)

    @pytest.mark.skipif(torch.cuda.is_available(), reason="GPU が無い環境でだけ確かめる")
    def test_gpu_requested_without_gpu(self, tmp_path: Path) -> None:
        _write_bundle(tmp_path / "bundles")
        out_dir = tmp_path / "runs"
        with pytest.raises(ValueError):
            run_training(
                _config(out_dir, train={"device": "cuda"}),
                config_name="synthetic",
                environ=ENVIRON,
                now=NOW,
                bundles_dir=tmp_path / "bundles",
            )
        self._assert_nothing_created(out_dir)

    def test_invalid_git_commit(self, tmp_path: Path) -> None:
        out_dir = tmp_path / "runs"
        with pytest.raises(ValueError):
            run_training(
                _config(out_dir),
                config_name="synthetic",
                environ={GIT_COMMIT_ENV_VAR: "../evil"},
                now=NOW,
                bundles_dir=tmp_path / "bundles",
            )
        self._assert_nothing_created(out_dir)

    def test_invalid_config_name(self, tmp_path: Path) -> None:
        out_dir = tmp_path / "runs"
        with pytest.raises(ValueError):
            run_training(
                _config(out_dir),
                config_name="bad name",
                environ=ENVIRON,
                now=NOW,
                bundles_dir=tmp_path / "bundles",
            )
        self._assert_nothing_created(out_dir)

    def test_existing_run_dir_is_not_overwritten(self, tmp_path: Path) -> None:
        out_dir = tmp_path / "runs"
        existing = out_dir / RUN_ID
        existing.mkdir(parents=True)
        (existing / "metrics.json").write_text("original", encoding="utf-8")
        with pytest.raises(ValueError):
            run_training(
                _config(out_dir),
                config_name="synthetic",
                environ=ENVIRON,
                now=NOW,
                bundles_dir=tmp_path / "bundles",
            )
        assert [p.name for p in existing.iterdir()] == ["metrics.json"]
        assert (existing / "metrics.json").read_text(encoding="utf-8") == "original"


# ---------------------------------------------------------------------------
# 止まり方: フォルダを作った後に止まる（実験フォルダと log.txt は残る）
# ---------------------------------------------------------------------------


@pytest.mark.usefixtures("restore_logging")
class TestStopsAfterCreatingRunDir:
    def test_missing_bundle_leaves_run_dir_and_log(self, tmp_path: Path) -> None:
        (tmp_path / "bundles").mkdir()
        out_dir = tmp_path / "runs"
        with pytest.raises(ValueError):
            run_training(
                _config(out_dir),
                config_name="synthetic",
                environ=ENVIRON,
                now=NOW,
                bundles_dir=tmp_path / "bundles",
            )
        run_dir = out_dir / RUN_ID
        assert (run_dir / "log.txt").is_file()
        for name in ("history.csv", "metrics.json", "split.json", "predictions.csv"):
            assert not (run_dir / name).exists()
        assert not (run_dir / "checkpoints" / "best.pth").exists()

    def test_image_size_mismatch_stops_before_split(self, tmp_path: Path) -> None:
        # バンドルの画像は 64×64，設定は 32×32 → 全件の事前検証で止まる（黙って除かない）
        _write_bundle(tmp_path / "bundles")
        out_dir = tmp_path / "runs"
        with pytest.raises(ValueError):
            run_training(
                _config(out_dir, data={"image_size": [32, 32]}),
                config_name="synthetic",
                environ=ENVIRON,
                now=NOW,
                bundles_dir=tmp_path / "bundles",
            )
        run_dir = out_dir / RUN_ID
        assert (run_dir / "log.txt").is_file()
        assert (run_dir / "config.yaml").is_file()
        for name in ("split.json", "history.csv", "metrics.json", "predictions.csv"):
            assert not (run_dir / name).exists()
