"""前任者の手法の比較の結合テスト（SPEC_02「前任者の手法との比較」・SPEC_01「回収ホワイトリスト」）.

`configs/predecessor/synthetic/` の設定を合成バンドル（scripts/make_synthetic_bundle.py）で流す．
CNN は時間を縮めるため画像を小さく・1 エポックにする（他の値は設定のまま）．

- 今のモデルの設定と `split.json` の分割が一致する．患者が train・val・held_out に跨らない
- `metrics.json` に `top_k`（top-1 は accuracy，クラス別 top-1 は recall と一致）と順位の種類
- SVM は `predictions.csv` の列名が `score_<クラス>`
- 疑似画像はファイルにしない．`metrics.json` に集計値だけを記録する．held_out は実画像の全枚数
- 回収対象に患者 ID・ハッシュが出ない．個票は回収ホワイトリストに入らない
- 手元用の設定は実データのバンドル（`tongue_color`）を読まない
"""

from __future__ import annotations

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

import pytest
import yaml

import tias_judge_model.cli.train as cli
from tias_judge_model.data.classes import CLASS_SLUGS
from tias_judge_model.remote.whitelist import is_pull_allowed

CONFIGS_DIR = Path(__file__).resolve().parents[2] / "configs" / "predecessor" / "synthetic"
PER_DIR = 8
N_IMAGES = 9 * PER_DIR
GIT = "abc1234"
ID_PREFIX = "SYN_"
FAST_TRAIN = {"image_size": 32, "max_epochs": 1, "amp": False}
# 実験ディレクトリに出てよいもの（CNN は history.csv と学習曲線が加わる．checkpoints は別に見る）
EXPECTED_FILES = {
    "config.yaml",
    "log.txt",
    "metrics.json",
    "confusion_matrix.csv",
    "split.json",
    "predictions.csv",
    "figures/confusion_matrix_all.png",
    "figures/confusion_matrix_common.png",
}
CNN_ONLY_FILES = {"history.csv", "figures/learning_curves.png"}


def _invoke(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 = cli.main(argv)
    finally:
        root_logger.removeHandler(handler)
        root_logger.setLevel(old_level)
    return rc, out.getvalue() + err.getvalue()


@pytest.fixture(scope="module")
def env(tmp_path_factory: pytest.TempPathFactory, script_loader):
    tmp = tmp_path_factory.mktemp("predecessor")
    bundles = tmp / "bundles"
    script = script_loader("make_synthetic_bundle")
    assert script.main(["--out", str(bundles), "--per-dir", str(PER_DIR), "--seed", "0"]) == 0
    hashes = [p.stem for p in (bundles / script.DEFAULT_NAME / "v3" / "files").glob("*.png")]
    assert len(hashes) == N_IMAGES

    mp = pytest.MonkeyPatch()
    mp.setenv("TIASDATA_BUNDLES", str(bundles))
    mp.setenv("TIAS_DATA_ROOT", "/nonexistent/tias_data_root")
    mp.setenv("TIAS_GIT_COMMIT", GIT)
    try:
        yield {"tmp": tmp, "bundles": bundles, "hashes": hashes, "runs": {}}
    finally:
        mp.undo()


def _run(env: dict, command: str, stem: str, *, fast: bool = False, doc_edit=None) -> dict:
    # 同じ設定を何度も回さない（module 内で共有する）．
    key = (command, stem, fast)
    if doc_edit is None and key in env["runs"]:
        return env["runs"][key]
    doc = yaml.safe_load((CONFIGS_DIR / f"{stem}.yaml").read_text(encoding="utf-8"))
    if fast:
        doc["train"].update(FAST_TRAIN)
    if doc_edit is not None:
        doc_edit(doc)
    name = f"{stem}_{len(list(env['tmp'].glob('*.yaml')))}"
    config = env["tmp"] / f"{name}.yaml"
    config.write_text(yaml.safe_dump(doc), encoding="utf-8")
    out_root = env["tmp"] / f"runs_{name}"
    rc, console = _invoke([command, "--config", str(config), "--out-root", str(out_root)])
    assert rc == 0, console[-3000:]
    run_dirs = [p for p in out_root.iterdir() if p.is_dir()]
    assert len(run_dirs) == 1
    run = {"dir": run_dirs[0], "console": console}
    if doc_edit is None:
        env["runs"][key] = run
    return run


CNN_STEMS = [
    "cv_pred_resnet34_synthetic",
    "cv_pred_resnet34_color_shift_real_plus_pseudo_synthetic",
    "cv_pred_resnet34_color_shift_pseudo_only_synthetic",
]
SVM_STEMS = [
    "cv_color_svm_lateral_synthetic",
    "cv_color_svm_coat_removed_synthetic",
    "cv_color_svm_coat_removed_slide_synthetic",
]


def _cnn(env: dict, stem: str) -> dict:
    return _run(env, "cv", stem, fast=True)


def _svm(env: dict, stem: str) -> dict:
    return _run(env, "color-cv", stem)


def _baseline(env: dict) -> dict:
    # 今のモデルの設定に相当（拡張・疑似画像なし．同じ seed）
    key = ("cv", "baseline", True)
    if key in env["runs"]:
        return env["runs"][key]

    def edit(doc: dict) -> None:
        doc["model"]["name"] = "resnet18"
        doc["train"].pop("augmentation")

    run = _run(env, "cv", "cv_pred_resnet34_synthetic", fast=True, doc_edit=edit)
    env["runs"][key] = run
    return run


def _metrics(run: dict) -> dict:
    return json.loads((run["dir"] / "metrics.json").read_text(encoding="utf-8"))


def _split(run: dict) -> dict:
    return json.loads((run["dir"] / "split.json").read_text(encoding="utf-8"))


def _predictions(run: dict) -> list[dict[str, str]]:
    with (run["dir"] / "predictions.csv").open(encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f))


# --- 分割 ---


@pytest.mark.slow
@pytest.mark.parametrize("stem", CNN_STEMS)
def test_cnn_split_matches_the_baseline(env: dict, stem: str) -> None:
    assert _split(_cnn(env, stem)) == _split(_baseline(env))


@pytest.mark.slow
@pytest.mark.parametrize("stem", SVM_STEMS)
def test_svm_split_matches_the_baseline(env: dict, stem: str) -> None:
    assert _split(_svm(env, stem)) == _split(_baseline(env))


@pytest.mark.slow
@pytest.mark.parametrize("stem", [*CNN_STEMS, *SVM_STEMS])
def test_patients_do_not_cross_splits(env: dict, stem: str) -> None:
    run = _cnn(env, stem) if stem in CNN_STEMS else _svm(env, stem)
    held_seen: set[str] = set()
    for fold in _split(run)["folds"]:
        train, val, held = set(fold["train"]), set(fold["val"]), set(fold["held_out"])
        assert train and val and held
        assert not train & val
        assert not train & held
        assert not val & held
        assert not held_seen & held
        held_seen |= held


@pytest.mark.slow
def test_held_out_is_the_real_images_only(env: dict) -> None:
    # 疑似画像を入れても評価はちょうど実画像の全枚数．患者も held_out の患者のまま
    for stem in CNN_STEMS:
        run = _cnn(env, stem)
        rows = _predictions(run)
        assert len(rows) == N_IMAGES
        assert len({row["image_path"] for row in rows}) == N_IMAGES
        held_by_fold = {f["fold"]: set(f["held_out"]) for f in _split(run)["folds"]}
        for row in rows:
            assert row["patient_id"] in held_by_fold[int(row["fold"])]


# --- top_k ---


def _assert_top_k_consistent(subset: dict) -> None:
    top_k = subset["top_k"]
    assert top_k["top1"] == pytest.approx(subset["accuracy"])
    assert top_k["top2"] >= top_k["top1"]
    for slug, per_class in top_k["per_class"].items():
        assert slug in CLASS_SLUGS
        assert per_class["top1"] == pytest.approx(subset["per_class"][slug]["recall"])
        assert per_class["top2"] >= per_class["top1"]
        assert per_class["support"] >= 1


@pytest.mark.slow
@pytest.mark.parametrize(
    ("stem", "ranking"),
    [
        ("cv_pred_resnet34_synthetic", "softmax"),
        ("cv_pred_resnet34_color_shift_pseudo_only_synthetic", "softmax"),
        ("cv_color_svm_lateral_synthetic", "decision_function"),
        ("cv_color_svm_coat_removed_synthetic", "decision_function"),
    ],
)
def test_metrics_have_consistent_top_k(env: dict, stem: str, ranking: str) -> None:
    run = _cnn(env, stem) if stem in CNN_STEMS else _svm(env, stem)
    metrics = _metrics(run)
    assert metrics["environment"]["top_k_ranking"] == ranking
    for subset in metrics["pooled"].values():
        if subset is not None:
            _assert_top_k_consistent(subset)
    for fold in metrics["folds"]:
        for subset in fold["subsets"].values():
            if subset is not None:
                _assert_top_k_consistent(subset)
    assert metrics["mean_std"]["all"]["top_k"]["top2"]["n"] == 5


@pytest.mark.slow
def test_existing_logistic_also_outputs_top_k_with_predict_proba(env: dict) -> None:
    def edit(doc: dict) -> None:
        doc["color"] = {"classifier": "logistic", "max_side": 64, "logistic": {"c_values": [1.0]}}

    metrics = _metrics(_run(env, "color-cv", "cv_color_svm_lateral_synthetic", doc_edit=edit))
    assert metrics["environment"]["top_k_ranking"] == "predict_proba"
    _assert_top_k_consistent(metrics["pooled"]["all"])


# --- SVM の出力 ---


@pytest.mark.slow
@pytest.mark.parametrize(
    ("stem", "features", "model_name"),
    [
        ("cv_color_svm_lateral_synthetic", "deeptias_lateral", "color_svm_rbf_deeptias_lateral"),
        ("cv_color_svm_coat_removed_synthetic", "tongue_body", "color_svm_rbf_tongue_body"),
        ("cv_color_svm_coat_removed_slide_synthetic", "tongue_body", "color_svm_rbf_tongue_body"),
    ],
)
def test_svm_metrics_record_features_and_candidates(
    env: dict, stem: str, features: str, model_name: str
) -> None:
    metrics = _metrics(_svm(env, stem))
    assert metrics["environment"]["model_name"] == model_name
    assert metrics["color_classifier"]["classifier"] == "svm_rbf"
    assert metrics["color_classifier"]["features"] == features
    assert metrics["color_classifier"]["num_features"] == 15
    assert len(metrics["color_classifier"]["feature_names"]) == 15
    assert len(metrics["color_classifier"]["candidates"]) == 16
    for fold in metrics["folds"]:
        assert len(fold["candidates"]) == 16
        assert set(fold["selected_params"]) == {"C", "gamma"}
        assert fold["best_epoch"] is None


@pytest.mark.slow
def test_coat_removed_records_body_fraction(env: dict) -> None:
    for stem in SVM_STEMS[1:]:
        summary = _metrics(_svm(env, stem))["color_classifier"]["feature_summary"]
        fraction = summary["body_fraction"]
        assert 0.0 < fraction["min"] <= fraction["mean"] <= fraction["max"] < 1.0


@pytest.mark.slow
def test_thresholds_change_the_features(env: dict) -> None:
    final = _metrics(_svm(env, "cv_color_svm_coat_removed_synthetic"))
    slide = _metrics(_svm(env, "cv_color_svm_coat_removed_slide_synthetic"))
    assert (
        final["color_classifier"]["feature_summary"] != slide["color_classifier"]["feature_summary"]
    )


@pytest.mark.slow
def test_lateral_has_no_feature_summary(env: dict) -> None:
    metrics = _metrics(_svm(env, "cv_color_svm_lateral_synthetic"))
    assert metrics["color_classifier"]["feature_summary"] is None


@pytest.mark.slow
def test_svm_predictions_use_score_columns(env: dict) -> None:
    rows = _predictions(_svm(env, "cv_color_svm_lateral_synthetic"))
    assert len(rows) == N_IMAGES
    assert {f"score_{slug}" for slug in CLASS_SLUGS} <= set(rows[0])
    assert not [key for key in rows[0] if key.startswith("prob_")]


@pytest.mark.slow
def test_cnn_predictions_keep_prob_columns(env: dict) -> None:
    rows = _predictions(_cnn(env, "cv_pred_resnet34_synthetic"))
    assert {f"prob_{slug}" for slug in CLASS_SLUGS} <= set(rows[0])
    assert not [key for key in rows[0] if key.startswith("score_")]


# --- 疑似画像の記録 ---


@pytest.mark.slow
@pytest.mark.parametrize(
    ("stem", "mode"),
    [
        ("cv_pred_resnet34_color_shift_real_plus_pseudo_synthetic", "real_plus_pseudo"),
        ("cv_pred_resnet34_color_shift_pseudo_only_synthetic", "pseudo_only"),
    ],
)
def test_pseudo_metrics_record_counts_and_statistics(env: dict, stem: str, mode: str) -> None:
    metrics = _metrics(_cnn(env, stem))
    assert metrics["color_shift_pseudo_mode"] == mode
    for fold in metrics["folds"]:
        record = fold["color_shift_pseudo"]
        assert record["mode"] == mode
        real = record["real_counts"]
        pseudo = record["pseudo_counts"]
        largest = max(real.values())
        for slug in CLASS_SLUGS:
            if mode == "pseudo_only":
                assert pseudo[slug] == largest
                expected = largest
            else:
                assert real[slug] + pseudo[slug] == largest
                expected = largest
            # class_counts は疑似画像を含めた枚数（SPEC_02）
            assert fold["class_balance"]["class_counts"][slug] == expected
        assert set(record["class_lab_mean"]) == set(CLASS_SLUGS)
        assert set(record["class_lab_std"]) == set(CLASS_SLUGS)
        assert record["max_target_error"] >= 0.0
        assert record["generation_seconds"] >= 0.0


@pytest.mark.slow
def test_runs_without_pseudo_do_not_record_it(env: dict) -> None:
    metrics = _metrics(_cnn(env, "cv_pred_resnet34_synthetic"))
    assert "color_shift_pseudo_mode" not in metrics
    assert all("color_shift_pseudo" not in fold for fold in metrics["folds"])


@pytest.mark.slow
def test_pseudo_generation_is_reproducible_between_runs(env: dict) -> None:
    # 同じ seed なら目標色の統計も枚数も同じ（秒数を除く）
    def edit(doc: dict) -> None:
        doc["train"].update(FAST_TRAIN)

    stem = "cv_pred_resnet34_color_shift_real_plus_pseudo_synthetic"
    first = _metrics(_cnn(env, stem))
    second = _metrics(_run(env, "cv", stem, doc_edit=edit))
    for a, b in zip(first["folds"], second["folds"], strict=True):
        record_a = {**a["color_shift_pseudo"], "generation_seconds": 0}
        record_b = {**b["color_shift_pseudo"], "generation_seconds": 0}
        assert record_a == record_b


# --- 保存しないこと・回収 ---


def _files(run_dir: Path) -> set[str]:
    return {
        p.relative_to(run_dir).as_posix()
        for p in run_dir.rglob("*")
        if p.is_file() and p.parent.name != "checkpoints"
    }


@pytest.mark.slow
@pytest.mark.parametrize("stem", CNN_STEMS)
def test_cnn_run_outputs_only_the_listed_files(env: dict, stem: str) -> None:
    # 疑似画像をファイルにしない
    assert _files(_cnn(env, stem)["dir"]) == EXPECTED_FILES | CNN_ONLY_FILES


@pytest.mark.slow
@pytest.mark.parametrize("stem", SVM_STEMS)
def test_svm_run_outputs_only_the_listed_files(env: dict, stem: str) -> None:
    assert _files(_svm(env, stem)["dir"]) == EXPECTED_FILES


@pytest.mark.slow
@pytest.mark.parametrize("stem", [*CNN_STEMS, *SVM_STEMS])
def test_individual_records_are_outside_the_whitelist(env: dict, stem: str) -> None:
    run = _cnn(env, stem) if stem in CNN_STEMS else _svm(env, stem)
    run_dir = run["dir"]
    for name in ("split.json", "predictions.csv"):
        assert (run_dir / name).is_file()
        assert not is_pull_allowed(name, with_checkpoints=True)
    for rel in _files(run_dir) - {"split.json", "predictions.csv"}:
        assert is_pull_allowed(rel, with_checkpoints=False), rel


@pytest.mark.slow
@pytest.mark.parametrize("stem", [*CNN_STEMS, *SVM_STEMS])
def test_recoverable_outputs_have_no_identifiers(env: dict, stem: str) -> None:
    run = _cnn(env, stem) if stem in CNN_STEMS else _svm(env, stem)
    texts = {"console": run["console"]}
    for rel in _files(run["dir"]):
        if is_pull_allowed(rel, with_checkpoints=False) and not rel.endswith(".png"):
            texts[rel] = (run["dir"] / rel).read_text(encoding="utf-8")
    assert "log.txt" in texts
    for name, text in texts.items():
        assert ID_PREFIX 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_individual_records_do_contain_ids_so_the_check_above_is_meaningful(env: dict) -> None:
    run = _svm(env, "cv_color_svm_lateral_synthetic")
    assert ID_PREFIX in (run["dir"] / "split.json").read_text(encoding="utf-8")


@pytest.mark.slow
def test_config_yaml_records_the_color_changing_settings(env: dict) -> None:
    # 色を変える処理を有効にした実験は，回収する config.yaml から分かること
    run = _cnn(env, "cv_pred_resnet34_color_shift_pseudo_only_synthetic")
    doc = yaml.safe_load((run["dir"] / "config.yaml").read_text(encoding="utf-8"))
    assert doc["config"]["train"]["augmentation"]["color_jitter"]["hue"] == 0.05
    assert doc["config"]["train"]["color_shift_pseudo"]["mode"] == "pseudo_only"
    assert doc["run"]["data_bundle"]["name"] == "tongue_color_synthetic"


@pytest.mark.slow
def test_config_yaml_records_the_svm_settings(env: dict) -> None:
    run = _svm(env, "cv_color_svm_coat_removed_slide_synthetic")
    doc = yaml.safe_load((run["dir"] / "config.yaml").read_text(encoding="utf-8"))
    assert doc["config"]["color"]["classifier"] == "svm_rbf"
    assert doc["config"]["color"]["features"] == "tongue_body"
    assert list(doc["config"]["color"]["coat_removal"]["yellow"]["h"]) == [0, 20]
    assert doc["run"]["data_bundle"]["name"] == "tongue_color_synthetic"


@pytest.mark.slow
def test_summarize_cv_skips_the_unregistered_models(
    env: dict, script_loader, capsys: pytest.CaptureFixture[str]
) -> None:
    # SPEC_02「今のモデルと比べるときの注意」: 登録されていないモデルの run は表に載らない
    run = _svm(env, "cv_color_svm_lateral_synthetic")
    script_loader("summarize_cv").main(run["dir"].parent)
    assert "svm" not in capsys.readouterr().out


# --- 実データを読まないこと・実験ディレクトリの前で止まること ---


def _write_doc(path: Path, doc: dict) -> Path:
    path.write_text(yaml.safe_dump(doc), encoding="utf-8")
    return path


@pytest.mark.parametrize("stem", [*CNN_STEMS, *SVM_STEMS])
def test_local_config_does_not_read_the_real_bundle_name(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, stem: str, bundle_writer
) -> None:
    # サーバの様子を真似る: バンドルの置き場所に tongue_color の版 3 だけがある
    from PIL import Image

    png = tmp_path / "x.png"
    Image.new("RGB", (4, 4), (10, 20, 30)).save(png)
    item = {"data": png.read_bytes(), "subject_id": "S1", "label": "red", "severity": "strong"}
    bundle_writer(tmp_path / "bundles", [item], version=3)
    monkeypatch.setenv("TIASDATA_BUNDLES", str(tmp_path / "bundles"))

    out_root = tmp_path / "runs"
    command = "cv" if stem in CNN_STEMS else "color-cv"
    rc, console = _invoke(
        [command, "--config", str(CONFIGS_DIR / f"{stem}.yaml"), "--out-root", str(out_root)]
    )

    assert rc == 1
    assert "tongue_color_synthetic" in console
    # 学習も特徴抽出も始まらない（画像を読まずに止まる）
    assert "読み込んだ" not in console
    run_dir = next(out_root.iterdir())
    assert not (run_dir / "metrics.json").exists()
    assert not (run_dir / "config.yaml").exists()


def test_deeptias_with_data_root_stops_before_creating_run_dir(tmp_path: Path) -> None:
    config = _write_doc(
        tmp_path / "bad.yaml",
        {
            "data": {"root": str(tmp_path / "unused")},
            "color": {"classifier": "svm_rbf", "features": "deeptias_lateral"},
        },
    )
    out_root = tmp_path / "runs"
    rc, console = _invoke(["color-cv", "--config", str(config), "--out-root", str(out_root)])
    assert rc == 1
    assert "data.bundle" in console
    assert not out_root.exists()


def test_svm_with_class_weighting_stops_before_creating_run_dir(tmp_path: Path) -> None:
    config = _write_doc(
        tmp_path / "bad.yaml",
        {
            "data": {"bundle": {"name": "tongue_color_synthetic", "version": 3}},
            "train": {"class_weighting": "inverse"},
            "color": {"classifier": "svm_rbf", "features": "deeptias_lateral"},
        },
    )
    out_root = tmp_path / "runs"
    rc, _ = _invoke(["color-cv", "--config", str(config), "--out-root", str(out_root)])
    assert rc == 1
    assert not out_root.exists()


@pytest.mark.parametrize("command", ["color-cv", "color-export"])
@pytest.mark.parametrize(
    ("train", "key"),
    [
        pytest.param(
            {"color_shift_pseudo": {"mode": "pseudo_only"}}, "color_shift_pseudo", id="pseudo_only"
        ),
        pytest.param(
            {"color_shift_pseudo": {"mode": "real_plus_pseudo"}},
            "color_shift_pseudo",
            id="real_plus_pseudo",
        ),
        pytest.param(
            {
                "augmentation": {
                    "color_jitter": {
                        "brightness": 0.05,
                        "contrast": 0.05,
                        "saturation": 0.05,
                        "hue": 0.05,
                    }
                }
            },
            "color_jitter",
            id="color_jitter",
        ),
    ],
)
def test_image_only_settings_stop_before_creating_run_dir(
    tmp_path: Path, command: str, train: dict, key: str
) -> None:
    # 画像で学習しないので効かない設定（SPEC_02「分類器と候補の選び方」）
    config = _write_doc(
        tmp_path / "bad.yaml",
        {
            "data": {"bundle": {"name": "tongue_color_synthetic", "version": 3}},
            "train": train,
            "color": {"classifier": "logistic", "features": "color_stats"},
        },
    )
    out_root = tmp_path / "runs"
    rc, console = _invoke([command, "--config", str(config), "--out-root", str(out_root)])
    assert rc == 1
    assert key in console
    assert not out_root.exists()


def test_export_with_other_features_stops_before_creating_run_dir(tmp_path: Path) -> None:
    config = _write_doc(
        tmp_path / "bad.yaml",
        {
            "data": {"bundle": {"name": "tongue_color_synthetic", "version": 3}},
            "color": {"classifier": "logistic", "features": "deeptias_lateral"},
        },
    )
    out_root = tmp_path / "runs"
    rc, console = _invoke(["color-export", "--config", str(config), "--out-root", str(out_root)])
    assert rc == 1
    assert "color_stats" in console
    assert not out_root.exists()


def test_invalid_predecessor_settings_stop_before_creating_run_dir(tmp_path: Path) -> None:
    config = _write_doc(
        tmp_path / "bad.yaml",
        {
            "data": {"root": str(tmp_path / "unused")},
            "train": {"color_shift_pseudo": {"mode": "pseudo_only"}, "class_weighting": "inverse"},
        },
    )
    out_root = tmp_path / "runs"
    rc, _ = _invoke(["cv", "--config", str(config), "--out-root", str(out_root)])
    assert rc == 1
    assert not out_root.exists()
