"""実験の出力 `runs/<実験ID>/` の土台（`training/run_artifacts.py`）のテスト.

期待値は SPEC_01「実験の出力」を基準にする．ファイル I/O はすべて `tmp_path` で行う．
"""

from __future__ import annotations

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

import pydantic
import pytest
import yaml

from tongue_seg_model.schema import ExperimentConfig
from tongue_seg_model.training.run_artifacts import (
    CHECKPOINTS_DIRNAME,
    CONFIG_FILENAME,
    FIGURES_DIRNAME,
    GIT_COMMIT_ENV_VAR,
    LOG_FILENAME,
    NO_GIT,
    BundleFingerprint,
    build_config_document,
    configure_logging,
    create_run_dir,
    load_run_config,
    make_run_id,
    resolve_git_commit,
    resolve_run_dir,
    validate_run_id,
    write_config_yaml,
)

SHA = "0123456789abcdef" * 4
RUN_ID_RE = re.compile(r"^\d{8}-\d{6}_[A-Za-z0-9][A-Za-z0-9._-]*_[A-Za-z0-9][A-Za-z0-9_-]*$")


def _config(**sections: Any) -> ExperimentConfig:
    raw: dict[str, Any] = {"data": {"bundle": {"name": "synthetic", "version": 1}}}
    raw.update(sections)
    return ExperimentConfig.model_validate(raw)


@pytest.fixture
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)


# ---------------------------------------------------------------------------
# 定数（SPEC_01 のファイル名）
# ---------------------------------------------------------------------------


def test_artifact_names_match_spec01() -> None:
    assert CONFIG_FILENAME == "config.yaml"
    assert LOG_FILENAME == "log.txt"
    assert FIGURES_DIRNAME == "figures"
    assert CHECKPOINTS_DIRNAME == "checkpoints"
    assert NO_GIT == "nogit"


# ---------------------------------------------------------------------------
# resolve_git_commit
# ---------------------------------------------------------------------------


class TestResolveGitCommit:
    def test_returns_nogit_without_env_var(self) -> None:
        assert resolve_git_commit({}) == "nogit"

    def test_returns_nogit_for_empty_value(self) -> None:
        assert resolve_git_commit({GIT_COMMIT_ENV_VAR: ""}) == "nogit"
        assert resolve_git_commit({GIT_COMMIT_ENV_VAR: "   "}) == "nogit"

    def test_returns_short_hash(self) -> None:
        assert resolve_git_commit({GIT_COMMIT_ENV_VAR: "a1b2c3d"}) == "a1b2c3d"

    def test_accepts_dirty_suffix(self) -> None:
        assert resolve_git_commit({GIT_COMMIT_ENV_VAR: "a1b2c3d-dirty"}) == "a1b2c3d-dirty"

    def test_strips_surrounding_whitespace(self) -> None:
        assert resolve_git_commit({GIT_COMMIT_ENV_VAR: " a1b2c3d\n"}) == "a1b2c3d"

    @pytest.mark.parametrize(
        "value",
        [
            "../evil",
            "a1b2c3d/x",
            "a1b2 c3d",
            "-dirty",
            "a1b2c3d;rm",
            "a" * 65,
        ],
    )
    def test_rejects_invalid_hash(self, value: str) -> None:
        with pytest.raises(ValueError):
            resolve_git_commit({GIT_COMMIT_ENV_VAR: value})

    def test_reads_os_environ_by_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setenv(GIT_COMMIT_ENV_VAR, "deadbee")
        assert resolve_git_commit() == "deadbee"
        monkeypatch.delenv(GIT_COMMIT_ENV_VAR)
        assert resolve_git_commit() == "nogit"


# ---------------------------------------------------------------------------
# make_run_id
# ---------------------------------------------------------------------------


class TestMakeRunId:
    def test_format_is_timestamp_config_name_and_hash(self) -> None:
        run_id = make_run_id(datetime(2026, 11, 18, 9, 5, 7), "resunet", "a1b2c3d")
        assert run_id == "20261118-090507_resunet_a1b2c3d"

    def test_includes_dirty_suffix(self) -> None:
        run_id = make_run_id(datetime(2026, 1, 2, 3, 4, 5), "synthetic", "a1b2c3d-dirty")
        assert run_id == "20260102-030405_synthetic_a1b2c3d-dirty"
        assert RUN_ID_RE.match(run_id)

    def test_includes_nogit(self) -> None:
        run_id = make_run_id(datetime(2026, 1, 2, 3, 4, 5), "synthetic", NO_GIT)
        assert run_id.endswith("_synthetic_nogit")

    def test_config_name_from_path_stem(self) -> None:
        stem = Path("configs/resunet.yaml").stem
        assert make_run_id(datetime(2026, 1, 1), stem, "abc1234") == (
            "20260101-000000_resunet_abc1234"
        )

    @pytest.mark.parametrize("name", ["", "../x", "a/b", "a b", "a\\b"])
    def test_rejects_unsafe_config_name(self, name: str) -> None:
        with pytest.raises(ValueError):
            make_run_id(datetime(2026, 1, 1), name, "abc1234")

    @pytest.mark.parametrize("commit", ["", "../x", "a/b"])
    def test_rejects_unsafe_git_commit(self, commit: str) -> None:
        with pytest.raises(ValueError):
            make_run_id(datetime(2026, 1, 1), "resunet", commit)

    @pytest.mark.parametrize(
        ("name", "commit"), [("resunet\n", "abc1234"), ("resunet", "abc1234\n")]
    )
    def test_rejects_trailing_newline(self, name: str, commit: str) -> None:
        with pytest.raises(ValueError):
            make_run_id(datetime(2026, 1, 1), name, commit)


# ---------------------------------------------------------------------------
# create_run_dir
# ---------------------------------------------------------------------------


class TestCreateRunDir:
    def test_creates_run_dir_with_figures_and_checkpoints(self, tmp_path: Path) -> None:
        out_dir = tmp_path / "runs"
        run_dir = create_run_dir(out_dir, "20260101-000000_synthetic_nogit")
        assert run_dir == out_dir / "20260101-000000_synthetic_nogit"
        assert run_dir.is_dir()
        assert (run_dir / "figures").is_dir()
        assert (run_dir / "checkpoints").is_dir()

    def test_creates_missing_parent_out_dir(self, tmp_path: Path) -> None:
        out_dir = tmp_path / "nested" / "runs"
        run_dir = create_run_dir(out_dir, "rid")
        assert run_dir.is_dir()

    def test_does_not_overwrite_existing_run_dir(self, tmp_path: Path) -> None:
        run_dir = create_run_dir(tmp_path, "rid")
        marker = run_dir / CONFIG_FILENAME
        marker.write_text("original", encoding="utf-8")
        with pytest.raises(ValueError):
            create_run_dir(tmp_path, "rid")
        assert marker.read_text(encoding="utf-8") == "original"

    def test_existing_dir_without_subdirs_is_also_refused(self, tmp_path: Path) -> None:
        (tmp_path / "rid").mkdir()
        with pytest.raises(ValueError):
            create_run_dir(tmp_path, "rid")


# ---------------------------------------------------------------------------
# BundleFingerprint
# ---------------------------------------------------------------------------


class TestBundleFingerprint:
    def test_to_dict(self) -> None:
        fp = BundleFingerprint("synthetic", 1, SHA)
        assert fp.to_dict() == {"name": "synthetic", "version": 1, "manifest_sha256": SHA}

    @pytest.mark.parametrize(
        ("name", "version", "sha"),
        [
            ("", 1, SHA),
            ("a", 0, SHA),
            ("a", True, SHA),
            ("a", "1", SHA),
            ("a", 1, SHA[:-1]),
            ("a", 1, SHA.upper()),
            ("a", 1, "g" * 64),
            ("a", 1, SHA + "\n"),
        ],
    )
    def test_rejects_invalid_values(self, name: str, version: Any, sha: str) -> None:
        with pytest.raises(ValueError):
            BundleFingerprint(name, version, sha)


# ---------------------------------------------------------------------------
# build_config_document / write_config_yaml
# ---------------------------------------------------------------------------


class TestConfigDocument:
    def test_contains_run_record(self) -> None:
        config = _config(train={"seed": 7})
        fp = BundleFingerprint("synthetic", 1, SHA)
        doc = build_config_document(
            config, run_id="rid", git_commit="a1b2c3d-dirty", data_bundle=fp
        )
        assert doc["run"] == {
            "id": "rid",
            "git_commit": "a1b2c3d-dirty",
            "seed": 7,
            "data_bundle": {"name": "synthetic", "version": 1, "manifest_sha256": SHA},
        }

    def test_bundle_fingerprint_defaults_to_null(self) -> None:
        doc = build_config_document(_config(), run_id="rid", git_commit=NO_GIT)
        assert doc["run"]["data_bundle"] is None
        assert doc["run"]["git_commit"] == "nogit"
        assert doc["run"]["seed"] == 2021

    def test_config_contains_all_resolved_items(self) -> None:
        doc = build_config_document(_config(), run_id="rid", git_commit=NO_GIT)
        cfg = doc["config"]
        assert set(cfg) == {"data", "augment", "model", "loss", "train", "export", "run"}
        # 書いていない項目も既定値で埋まっている
        assert cfg["train"]["batch_size"] == 16
        assert cfg["train"]["learning_rate"] == pytest.approx(1e-4)
        assert cfg["train"]["max_epochs"] == 300
        assert cfg["train"]["early_stopping_patience"] == 30
        assert cfg["loss"] == {"bce_weight": 0.5, "bce_input": "sigmoid"}
        assert cfg["augment"]["hflip_prob"] == 0.5
        assert cfg["export"]["opset"] == 11
        assert list(cfg["data"]["image_size"]) == [256, 256]

    def test_written_yaml_round_trips(self, tmp_path: Path) -> None:
        config = _config(
            model={"pretrained": False},
            train={"batch_size": 4, "max_epochs": 3, "device": "cpu"},
            run={"out_dir": str(tmp_path / "runs")},
        )
        fp = BundleFingerprint("synthetic", 1, SHA)
        doc = build_config_document(config, run_id="rid", git_commit="abc1234", data_bundle=fp)
        path = write_config_yaml(tmp_path, doc)

        assert path == tmp_path / "config.yaml"
        loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
        assert loaded["run"] == {
            "id": "rid",
            "git_commit": "abc1234",
            "seed": 2021,
            "data_bundle": {"name": "synthetic", "version": 1, "manifest_sha256": SHA},
        }
        # 書き出した設定をスキーマで読み戻すと元と同じ設定になる
        assert ExperimentConfig.model_validate(loaded["config"]) == config

    def test_written_yaml_has_null_bundle_when_absent(self, tmp_path: Path) -> None:
        doc = build_config_document(_config(), run_id="rid", git_commit=NO_GIT)
        path = write_config_yaml(tmp_path, doc)
        text = path.read_text(encoding="utf-8")
        loaded = yaml.safe_load(text)
        assert "data_bundle" in loaded["run"]
        assert loaded["run"]["data_bundle"] is None


# ---------------------------------------------------------------------------
# configure_logging
# ---------------------------------------------------------------------------


def _own_handlers() -> list[logging.Handler]:
    return [
        h
        for h in logging.getLogger().handlers
        if h.get_name() and h.get_name().startswith("tongue_seg_model.")
    ]


@pytest.mark.usefixtures("restore_logging")
class TestConfigureLogging:
    def test_writes_to_log_txt(self, tmp_path: Path) -> None:
        configure_logging(tmp_path)
        logging.getLogger("tongue_seg_model.test").info("hello-log-file")
        for h in _own_handlers():
            h.flush()
        text = (tmp_path / "log.txt").read_text(encoding="utf-8")
        assert "hello-log-file" in text

    def test_writes_to_stderr_not_stdout(
        self, tmp_path: Path, capsys: pytest.CaptureFixture[str]
    ) -> None:
        configure_logging(tmp_path)
        logging.getLogger("tongue_seg_model.test").info("hello-console")
        captured = capsys.readouterr()
        assert "hello-console" in captured.err
        assert "hello-console" not in captured.out

    def test_calling_twice_does_not_duplicate_handlers(self, tmp_path: Path) -> None:
        configure_logging(tmp_path)
        configure_logging(tmp_path)
        assert len(_own_handlers()) == 2
        logging.getLogger("tongue_seg_model.test").info("only-once")
        for h in _own_handlers():
            h.flush()
        text = (tmp_path / "log.txt").read_text(encoding="utf-8")
        assert text.count("only-once") == 1

    def test_switching_run_dir_moves_file_output(self, tmp_path: Path) -> None:
        first = tmp_path / "first"
        second = tmp_path / "second"
        first.mkdir()
        second.mkdir()
        configure_logging(first)
        configure_logging(second)
        logging.getLogger("tongue_seg_model.test").info("to-second")
        for h in _own_handlers():
            h.flush()
        assert "to-second" in (second / "log.txt").read_text(encoding="utf-8")
        assert "to-second" not in (first / "log.txt").read_text(encoding="utf-8")

    def test_without_run_dir_only_console(self, tmp_path: Path) -> None:
        configure_logging(tmp_path)
        configure_logging(None)
        handlers = _own_handlers()
        assert len(handlers) == 1
        assert not isinstance(handlers[0], logging.FileHandler)

    def test_does_not_remove_foreign_handlers(self, tmp_path: Path) -> None:
        root = logging.getLogger()
        foreign = logging.NullHandler()
        root.addHandler(foreign)
        try:
            configure_logging(tmp_path)
            configure_logging(tmp_path)
            assert foreign in root.handlers
        finally:
            root.removeHandler(foreign)

    def test_sets_level(self, tmp_path: Path) -> None:
        configure_logging(tmp_path, level=logging.WARNING)
        assert logging.getLogger().level == logging.WARNING
        logging.getLogger("tongue_seg_model.test").info("suppressed-info")
        for h in _own_handlers():
            h.flush()
        assert "suppressed-info" not in (tmp_path / "log.txt").read_text(encoding="utf-8")


# ---------------------------------------------------------------------------
# 外から受け取った実験 ID の検証・実験ディレクトリの解決・設定の読み戻し（tsm-export の入口）
# ---------------------------------------------------------------------------

VALID_RUN_ID = "20261119-102030_synthetic_abc1234-dirty"


class TestValidateRunId:
    @pytest.mark.parametrize(
        "run_id",
        [
            VALID_RUN_ID,
            "20261119-115704_synthetic_nogit",
            "20260101-000000_resunet.v2_0123abc",
            "20260101-000000_a_b",
        ],
    )
    def test_accepts_ids_made_by_make_run_id(self, run_id: str) -> None:
        assert validate_run_id(run_id) == run_id

    def test_round_trips_make_run_id(self) -> None:
        run_id = make_run_id(datetime(2026, 11, 19, 10, 20, 30), "synthetic", "abc1234-dirty")
        assert validate_run_id(run_id) == run_id

    @pytest.mark.parametrize(
        "run_id",
        [
            "",
            "..",
            ".",
            "../20261119-102030_synthetic_abc1234",
            "20261119-102030_synthetic_abc1234/..",
            "20261119-102030_synthetic_abc1234/../x",
            "20261119-102030_synthetic_abc1234\\..",
            "..\\20261119-102030_synthetic_abc1234",
            "20261119-102030_../_abc1234",
            "20261119-102030_.._abc1234",
            "20261119-102030_a/b_abc1234",
            "20261119-102030_a\\b_abc1234",
            "20261119-102030_synthetic_abc1234\n",
            "\n20261119-102030_synthetic_abc1234",
            "20261119-102030_synthetic_abc1234 ",
            " 20261119-102030_synthetic_abc1234",
            "20261119-102030_synthetic_abc1234\x00",
            "C:\\20261119-102030_synthetic_abc1234",
            "/20261119-102030_synthetic_abc1234",
            "20261119-102030_synthetic",
            "2026111-102030_synthetic_abc1234",
            "20261119102030_synthetic_abc1234",
            "20261119-102030__abc1234",
            "20261119-102030_synthetic_",
            "20261119-102030_synthetic_.abc",
            "20261119-102030_-synthetic_abc1234",
            "20261119-102030_synthetic_abc.1234",
        ],
    )
    def test_rejects_ids_that_are_not_run_ids(self, run_id: str) -> None:
        with pytest.raises(ValueError, match="実験 ID"):
            validate_run_id(run_id)

    def test_rejects_too_long_parts(self) -> None:
        with pytest.raises(ValueError):
            validate_run_id("20261119-102030_" + "a" * 65 + "_abc1234")
        with pytest.raises(ValueError):
            validate_run_id("20261119-102030_synthetic_" + "a" * 65)

    def test_accepts_64_char_parts(self) -> None:
        run_id = "20261119-102030_" + "a" * 64 + "_" + "b" * 64
        assert validate_run_id(run_id) == run_id


class TestResolveRunDir:
    def test_returns_existing_run_dir(self, tmp_path: Path) -> None:
        run_dir = create_run_dir(tmp_path, VALID_RUN_ID)
        assert resolve_run_dir(tmp_path, VALID_RUN_ID) == run_dir

    def test_missing_run_dir_is_value_error(self, tmp_path: Path) -> None:
        with pytest.raises(ValueError, match="実験ディレクトリが無い"):
            resolve_run_dir(tmp_path, VALID_RUN_ID)

    def test_file_instead_of_dir_is_value_error(self, tmp_path: Path) -> None:
        (tmp_path / VALID_RUN_ID).write_text("x", encoding="utf-8")
        with pytest.raises(ValueError, match="実験ディレクトリが無い"):
            resolve_run_dir(tmp_path, VALID_RUN_ID)

    @pytest.mark.parametrize("run_id", ["..", ".", "../outside", "sub/..", "", "x\\..\\.."])
    def test_cannot_point_outside_out_dir(self, tmp_path: Path, run_id: str) -> None:
        # 親・自分自身は実在するディレクトリだが，形式で止まること
        out_dir = tmp_path / "runs"
        out_dir.mkdir()
        (tmp_path / "outside").mkdir()
        (out_dir / "sub").mkdir()
        with pytest.raises(ValueError, match="実験 ID"):
            resolve_run_dir(out_dir, run_id)

    def test_existing_dir_with_trailing_newline_name_is_not_resolved(self, tmp_path: Path) -> None:
        # 改行付きの ID は形式で止まる（`$` の末尾改行の抜け道が無いこと）
        create_run_dir(tmp_path, VALID_RUN_ID)
        with pytest.raises(ValueError, match="実験 ID"):
            resolve_run_dir(tmp_path, VALID_RUN_ID + "\n")


class TestLoadRunConfig:
    def test_round_trips_written_config(self, tmp_path: Path) -> None:
        config = _config(
            data={"bundle": {"name": "synthetic", "version": 3}, "image_size": [64, 96]},
            export={"opset": 13},
        )
        write_config_yaml(
            tmp_path, build_config_document(config, run_id=VALID_RUN_ID, git_commit="abc1234")
        )
        loaded = load_run_config(tmp_path)
        assert isinstance(loaded, ExperimentConfig)
        assert loaded == config
        assert loaded.export.opset == 13
        assert tuple(loaded.data.image_size) == (64, 96)

    def test_missing_config_yaml_is_value_error(self, tmp_path: Path) -> None:
        with pytest.raises(ValueError, match=CONFIG_FILENAME):
            load_run_config(tmp_path)

    def test_broken_yaml_is_value_error(self, tmp_path: Path) -> None:
        (tmp_path / CONFIG_FILENAME).write_text("config: [unclosed\n", encoding="utf-8")
        with pytest.raises(ValueError, match=CONFIG_FILENAME):
            load_run_config(tmp_path)

    def test_non_utf8_is_value_error(self, tmp_path: Path) -> None:
        (tmp_path / CONFIG_FILENAME).write_bytes(b"config: \xff\xfe\x80\n")
        with pytest.raises(ValueError, match=CONFIG_FILENAME):
            load_run_config(tmp_path)

    @pytest.mark.parametrize(
        "text",
        ["", "- a\n- b\n", "run: {id: x}\n", "config: null\n", "config: [1, 2]\n", "config: 3\n"],
    )
    def test_document_without_config_mapping_is_value_error(
        self, tmp_path: Path, text: str
    ) -> None:
        (tmp_path / CONFIG_FILENAME).write_text(text, encoding="utf-8")
        with pytest.raises(ValueError, match="config"):
            load_run_config(tmp_path)

    def test_invalid_config_content_is_validation_error(self, tmp_path: Path) -> None:
        document = build_config_document(_config(), run_id=VALID_RUN_ID, git_commit="abc1234")
        document["config"]["export"]["opset"] = 6  # 7 以上のはず
        write_config_yaml(tmp_path, document)
        with pytest.raises(pydantic.ValidationError):
            load_run_config(tmp_path)

    def test_unknown_key_is_validation_error(self, tmp_path: Path) -> None:
        document = build_config_document(_config(), run_id=VALID_RUN_ID, git_commit="abc1234")
        document["config"]["unknown"] = 1
        write_config_yaml(tmp_path, document)
        with pytest.raises(pydantic.ValidationError):
            load_run_config(tmp_path)

    def test_config_dir_instead_of_file_is_value_error(self, tmp_path: Path) -> None:
        (tmp_path / CONFIG_FILENAME).mkdir()
        with pytest.raises(ValueError, match=CONFIG_FILENAME):
            load_run_config(tmp_path)
