"""`data.bundle` の設定での tias-train・tias-dataset の結合テスト.

仕様（SPEC の更新前のため確定した仕様として扱う）:

- 指紋（`{name, version, manifest_sha256}`）を `config.yaml` の `run.data_bundle`・`metrics.json`
  （cv・color-cv・color-export）・`dataset_summary.json`・`color_model.json` の
  `training.data_bundle` に記録する
- `data.bundle` があるとき `TIAS_DATA_ROOT` は無視する（`tias-remote run` が常に渡す）
- `survey` は全ファイルを照合する．`build-manifest` は bundle の設定を拒否して exit 1
- 回収対象の出力・ログ・標準出力に subject_id・ハッシュ・ファイル名を出さない
- 複数ラベルの患者を含むデータでも患者は分割をまたがない

バンドルは tmp に作る合成のもの．学習は極小設定で回す（slow）．
"""

from __future__ import annotations

import contextlib
import hashlib
import io
import json
import logging
from pathlib import Path

import pytest
import yaml

import tias_judge_model.cli.dataset as dataset_cli
import tias_judge_model.cli.train as train_cli
from tias_judge_model.deploy.color_model import load_color_model
from tias_judge_model.remote.whitelist import is_pull_allowed

SECRET = "SECRETSUBJ"
GIT = "abc1234"
N_FOLDS = 5
PER_DIR = 7
SPLIT_SEED = 3
BOGUS_ROOT = "/nonexistent/tias_data_root"
BUNDLE = {"name": "tongue_color", "version": 1}


def _data() -> dict:
    return {"bundle": BUNDLE, "severities": ["strong", "normal"]}


def _cnn_doc() -> dict:
    return {
        "data": _data(),
        "split": {"seed": SPLIT_SEED, "n_folds": N_FOLDS},
        "model": {"name": "resnet18", "pretrained": False},
        "train": {
            "image_size": 32,
            "batch_size": 8,
            "max_epochs": 1,
            "warmup_epochs": 0,
            "inner_val_ratio": 0.2,
            "num_workers": 0,
            "amp": False,
        },
    }


def _color_doc() -> dict:
    return {
        **_cnn_doc(),
        "color": {
            "classifier": "logistic",
            "max_side": 64,
            "logistic": {"c_values": [0.1, 1.0], "max_iter": 2000},
        },
    }


def _export_doc() -> dict:
    return {
        "data": _data(),
        "split": {"seed": SPLIT_SEED, "n_folds": N_FOLDS},
        "train": {"class_weighting": "inverse"},
        "color": {
            "classifier": "logistic",
            "max_side": 64,
            "logistic": {"c_values": [0.1, 1.0], "max_iter": 2000},
        },
    }


def _invoke(main, argv: list[str]) -> tuple[int, str]:
    root_logger = logging.getLogger()
    old_level = root_logger.level
    root_logger.setLevel(logging.INFO)
    out, err = io.StringIO(), io.StringIO()
    handler = logging.StreamHandler(err)
    root_logger.addHandler(handler)
    try:
        with contextlib.redirect_stdout(out):
            rc = main(argv)
    finally:
        root_logger.removeHandler(handler)
        root_logger.setLevel(old_level)
    return rc, out.getvalue() + err.getvalue()


def _write_config(tmp: Path, name: str, doc: dict) -> Path:
    path = tmp / f"{name}.yaml"
    path.write_text(yaml.safe_dump(doc), encoding="utf-8")
    return path


def _only_run_dir(out_root: Path) -> Path:
    dirs = [p for p in out_root.iterdir() if p.is_dir()]
    assert len(dirs) == 1
    return dirs[0]


@pytest.fixture(scope="module")
def env(tmp_path_factory: pytest.TempPathFactory, bundle_writer, bundle_items) -> dict:
    tmp = tmp_path_factory.mktemp("train_bundle")
    bundles_dir = tmp / "bundles"
    items = bundle_items(tmp / "synthetic", per_dir=PER_DIR, secret=SECRET)
    root = bundle_writer(bundles_dir, items)
    hashes = sorted(hashlib.sha256(item["data"]).hexdigest() for item in items)
    fingerprint = {
        **BUNDLE,
        "manifest_sha256": hashlib.sha256((root / "manifest.csv").read_bytes()).hexdigest(),
    }

    mp = pytest.MonkeyPatch()
    mp.setenv("TIASDATA_BUNDLES", str(bundles_dir))
    # tias-remote run は常に渡すので，実際の呼び出しと同じく設定した状態で動かす
    mp.setenv("TIAS_DATA_ROOT", BOGUS_ROOT)
    mp.setenv("TIAS_GIT_COMMIT", GIT)
    try:
        yield {
            "tmp": tmp,
            "bundles_dir": bundles_dir,
            "root": root,
            "items": items,
            "hashes": hashes,
            "fingerprint": fingerprint,
        }
    finally:
        mp.undo()


def _run(env: dict, main, command: str, name: str, doc: dict) -> dict:
    config = _write_config(env["tmp"], name, doc)
    out_root = env["tmp"] / f"runs_{name}"
    rc, console = _invoke(main, [command, "--config", str(config), "--out-root", str(out_root)])
    assert rc == 0, console[-2000:]
    return {"dir": _only_run_dir(out_root), "console": console}


@pytest.fixture(scope="module")
def cv_run(env: dict) -> dict:
    return _run(env, train_cli.main, "cv", "bundle_cv", _cnn_doc())


@pytest.fixture(scope="module")
def color_cv_run(env: dict) -> dict:
    return _run(env, train_cli.main, "color-cv", "bundle_color", _color_doc())


@pytest.fixture(scope="module")
def export_run(env: dict) -> dict:
    return _run(env, train_cli.main, "color-export", "bundle_export", _export_doc())


@pytest.fixture(scope="module")
def survey_run(env: dict) -> dict:
    return _run(env, dataset_cli.main, "survey", "bundle_survey", {"data": _data()})


def _read_json(path: Path) -> dict:
    return json.loads(path.read_text(encoding="utf-8"))


def _read_yaml(path: Path) -> dict:
    return yaml.safe_load(path.read_text(encoding="utf-8"))


def _assert_config_records_bundle(run_dir: Path, fingerprint: dict) -> None:
    document = _read_yaml(run_dir / "config.yaml")
    assert document["run"]["data_bundle"] == fingerprint
    assert document["config"]["data"]["bundle"] == BUNDLE
    # TIAS_DATA_ROOT を設定していても root にならない
    assert document["config"]["data"]["root"] is None


def _assert_no_identifiers(run: dict, env: dict) -> None:
    texts = {"console": run["console"]}
    for path in run["dir"].rglob("*"):
        rel = path.relative_to(run["dir"]).as_posix()
        assert SECRET not in rel
        if not path.is_file() or path.suffix == ".png":
            continue
        # 回収対象だけを調べる（split.json・predictions.csv はサーバに残るので患者 ID を含む）
        if is_pull_allowed(rel, with_checkpoints=False):
            texts[rel] = path.read_text(encoding="utf-8")
    assert "log.txt" in texts
    for name, text in texts.items():
        assert SECRET not in text, name
        assert ".png" not in text, name
        for sha256 in env["hashes"]:
            assert sha256[:12] not in text, name


# --- 指紋の記録 -----------------------------------------------------------------------------------


@pytest.mark.slow
def test_cv_records_fingerprint(env: dict, cv_run: dict) -> None:
    _assert_config_records_bundle(cv_run["dir"], env["fingerprint"])
    metrics = _read_json(cv_run["dir"] / "metrics.json")
    assert metrics["data_bundle"] == env["fingerprint"]


@pytest.mark.slow
def test_color_cv_records_fingerprint(env: dict, color_cv_run: dict) -> None:
    _assert_config_records_bundle(color_cv_run["dir"], env["fingerprint"])
    metrics = _read_json(color_cv_run["dir"] / "metrics.json")
    assert metrics["data_bundle"] == env["fingerprint"]


@pytest.mark.slow
def test_color_export_records_fingerprint(env: dict, export_run: dict) -> None:
    _assert_config_records_bundle(export_run["dir"], env["fingerprint"])
    assert _read_json(export_run["dir"] / "metrics.json")["data_bundle"] == env["fingerprint"]
    document = _read_json(export_run["dir"] / "color_model.json")
    assert document["training"]["data_bundle"] == env["fingerprint"]
    # 指紋を足しても参照実装で読める
    load_color_model(export_run["dir"] / "color_model.json")


@pytest.mark.slow
def test_survey_records_fingerprint(env: dict, survey_run: dict) -> None:
    _assert_config_records_bundle(survey_run["dir"], env["fingerprint"])
    summary = _read_json(survey_run["dir"] / "dataset_summary.json")
    assert summary["data_bundle"] == env["fingerprint"]


# --- バンドルの中身が使われること ---


@pytest.mark.slow
def test_survey_counts_bundle_contents(env: dict, survey_run: dict) -> None:
    summary = _read_json(survey_run["dir"] / "dataset_summary.json")
    total = summary["counts"]["total"]
    assert total["images"] == len(env["items"])
    assert total["patients"] == len({item["subject_id"] for item in env["items"]})
    assert summary["loading"]["unreadable"] == 0
    # 全グループで単一分割・K-fold の確認が実際に行われている
    assert "error" not in summary["split"]["kfold"]


def _held_out(run_dir: Path) -> list[list[str]]:
    # split.json はサーバに残るファイル．held_out の患者 ID の fold ごとのリスト
    split = _read_json(run_dir / "split.json")
    return [fold["held_out"] for fold in split["folds"]]


@pytest.mark.slow
def test_cv_keeps_multi_label_patients_on_one_side(env: dict, cv_run: dict) -> None:
    split = _read_json(cv_run["dir"] / "split.json")
    subjects = {item["subject_id"] for item in env["items"]}
    assert any(s.startswith(f"{SECRET}M") for s in subjects)
    held = [p for fold in split["folds"] for p in fold["held_out"]]
    assert sorted(held) == sorted(subjects)
    for fold in split["folds"]:
        assert set(fold["train"]).isdisjoint(fold["held_out"])
        assert set(fold["val"]).isdisjoint(fold["held_out"])
        assert set(fold["train"]).isdisjoint(fold["val"])
        assert set(fold["train"]) | set(fold["val"]) | set(fold["held_out"]) == subjects


@pytest.mark.slow
def test_cv_and_color_cv_share_the_split(cv_run: dict, color_cv_run: dict) -> None:
    assert _held_out(cv_run["dir"]) == _held_out(color_cv_run["dir"])


@pytest.mark.slow
def test_cv_evaluates_every_bundle_image(env: dict, cv_run: dict) -> None:
    metrics = _read_json(cv_run["dir"] / "metrics.json")
    assert metrics["n_folds"] == N_FOLDS
    # severities に関わらず held_out は全程度で評価する
    held = sum(fold["subsets"]["all"]["n"] for fold in metrics["folds"])
    assert held == len(env["items"])


# --- 個人情報 -------------------------------------------------------------------------------------


@pytest.mark.slow
@pytest.mark.parametrize("name", ["cv_run", "color_cv_run", "export_run", "survey_run"])
def test_outputs_have_no_subject_id_or_hash(
    env: dict, name: str, request: pytest.FixtureRequest
) -> None:
    _assert_no_identifiers(request.getfixturevalue(name), env)


# --- 異常系 ---------------------------------------------------------------------------------------


@pytest.mark.slow
def test_survey_stops_on_corrupted_file_without_hash(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bundle_writer, bundle_items
) -> None:
    bundles_dir = tmp_path / "bundles"
    items = bundle_items(tmp_path / "synthetic", per_dir=2, secret=SECRET)
    root = bundle_writer(bundles_dir, items)
    sha256 = hashlib.sha256(items[0]["data"]).hexdigest()
    (root / "files" / f"{sha256}.png").write_bytes(b"broken")
    monkeypatch.setenv("TIASDATA_BUNDLES", str(bundles_dir))
    monkeypatch.delenv("TIAS_DATA_ROOT", raising=False)

    config = _write_config(tmp_path, "survey", {"data": _data()})
    out_root = tmp_path / "runs"
    rc, console = _invoke(
        dataset_cli.main, ["survey", "--config", str(config), "--out-root", str(out_root)]
    )
    assert rc == 1
    assert sha256[:12] not in console
    assert SECRET not in console
    for path in out_root.rglob("*"):
        if path.is_file():
            text = path.read_text(encoding="utf-8")
            assert sha256[:12] not in text, path.name
            assert SECRET not in text, path.name
            assert ".png" not in text, path.name


def test_survey_does_not_log_hash_when_file_is_unreadable(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bundle_writer, bundle_items
) -> None:
    # 権限エラー等の OSError は CLI が「%s」でログに出す．パス（= ハッシュ）が残らないこと
    bundles_dir = tmp_path / "bundles"
    items = bundle_items(tmp_path / "synthetic", per_dir=2, secret=SECRET)
    bundle_writer(bundles_dir, items)
    monkeypatch.setenv("TIASDATA_BUNDLES", str(bundles_dir))
    monkeypatch.delenv("TIAS_DATA_ROOT", raising=False)

    def denied(path: Path) -> str:
        raise PermissionError(13, "Permission denied", str(path))

    monkeypatch.setattr("tiasdata.bundle.sha256_file", denied)
    config = _write_config(tmp_path, "survey", {"data": _data()})
    out_root = tmp_path / "runs"
    rc, console = _invoke(
        dataset_cli.main, ["survey", "--config", str(config), "--out-root", str(out_root)]
    )
    assert rc == 1
    written = "".join(p.read_text(encoding="utf-8") for p in out_root.rglob("*") if p.is_file())
    for item in items:
        sha256 = hashlib.sha256(item["data"]).hexdigest()
        assert sha256[:12] not in console
        assert sha256[:12] not in written


@pytest.mark.parametrize(
    ("command", "doc"),
    [("cv", _cnn_doc), ("color-cv", _color_doc), ("color-export", _export_doc)],
)
def test_train_stops_on_broken_image_without_hash(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bundle_writer, bundle_items, command, doc
) -> None:
    # cv 系は照合しないので，壊れた画像は読み込みで止まる（位置は件数で示す）
    bundles_dir = tmp_path / "bundles"
    items = bundle_items(tmp_path / "synthetic", per_dir=N_FOLDS, secret=SECRET)
    root = bundle_writer(bundles_dir, items)
    sha256 = hashlib.sha256(items[0]["data"]).hexdigest()
    (root / "files" / f"{sha256}.png").write_bytes(b"broken")
    monkeypatch.setenv("TIASDATA_BUNDLES", str(bundles_dir))
    monkeypatch.setenv("TIAS_DATA_ROOT", BOGUS_ROOT)
    monkeypatch.setenv("TIAS_GIT_COMMIT", GIT)
    config = _write_config(tmp_path, "broken", doc())
    rc, console = _invoke(
        train_cli.main, [command, "--config", str(config), "--out-root", str(tmp_path / "runs")]
    )
    assert rc == 1
    assert sha256[:12] not in console
    assert SECRET not in console
    assert ".png" not in console


@pytest.mark.parametrize("command", ["cv", "color-cv"])
def test_train_stops_when_bundle_is_missing(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command: str
) -> None:
    monkeypatch.setenv("TIASDATA_BUNDLES", str(tmp_path / "no_bundles"))
    monkeypatch.setenv("TIAS_DATA_ROOT", BOGUS_ROOT)
    doc = _color_doc() if command == "color-cv" else _cnn_doc()
    config = _write_config(tmp_path, "missing", doc)
    rc, console = _invoke(
        train_cli.main, [command, "--config", str(config), "--out-root", str(tmp_path / "runs")]
    )
    assert rc == 1
    assert str(tmp_path / "no_bundles") not in console


@pytest.mark.parametrize("env_root", [None, BOGUS_ROOT])
@pytest.mark.parametrize("extra", [[], ["--overwrite"]])
def test_build_manifest_rejects_bundle_config(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, env_root: str | None, extra: list[str]
) -> None:
    if env_root is None:
        monkeypatch.delenv("TIAS_DATA_ROOT", raising=False)
    else:
        monkeypatch.setenv("TIAS_DATA_ROOT", str(tmp_path / "env_root"))
    monkeypatch.chdir(tmp_path)
    config = _write_config(tmp_path, "bundle", {"data": {"bundle": BUNDLE}})
    before = sorted(p.name for p in tmp_path.iterdir())
    rc, console = _invoke(dataset_cli.main, ["build-manifest", "--config", str(config), *extra])
    assert rc == 1
    assert "build-manifest" in console
    # 何も書かない
    assert sorted(p.name for p in tmp_path.iterdir()) == before
