"""前任者の手法の比較の分割のテスト（SPEC_02「共通」「(3) 疑似画像」．**最重要**）.

- 新しい設定の分割は既存の設定（`configs/cv_<条件>.yaml`）と同じ（同じ seed）
- 同じ患者が train・val・held_out に跨らない（複数ラベルの患者を含むデータで）
- 疑似画像を入れても跨らない: 統計も元画像もその fold の学習用データだけから取り，検証用・
  held_out を変えても疑似画像は変わらない．held_out は実画像のまま

データは合成の manifest と小さな合成画像．疑似画像の検査は学習の前で打ち切るので速い．
"""

from __future__ import annotations

import hashlib
from pathlib import Path

import numpy as np
import pytest
from PIL import Image

import tias_judge_model.training.cross_validation as cv
from tias_judge_model.data.classes import ALL_DIR_NAMES, parse_dir_name
from tias_judge_model.data.images import load_letterboxed_images
from tias_judge_model.data.manifest import ManifestRecord
from tias_judge_model.data.split import make_kfold_splits
from tias_judge_model.schema import ExperimentConfig, load_config
from tias_judge_model.training.cross_validation import (
    PreparedFold,
    fold_seed,
    prepare_fold,
    run_cross_validation,
)

CONFIGS_DIR = Path(__file__).resolve().parents[2] / "configs"
PREDECESSOR_DIR = CONFIGS_DIR / "predecessor"
STEMS = (
    "cv_pred_resnet34",
    "cv_pred_resnet34_color_shift_real_plus_pseudo",
    "cv_pred_resnet34_color_shift_pseudo_only",
    "cv_color_svm_lateral",
    "cv_color_svm_coat_removed",
    "cv_color_svm_coat_removed_slide",
)
CONDITIONS = ("with_mild", "without_mild")


def _records(seed: int = 0, n_patients: int = 180) -> list[ManifestRecord]:
    # 1 人が 1〜3 枚を持ち，画像ごとに別のラベルを持ちうる（SPEC_02「データ分割」）．
    rng = np.random.default_rng(seed)
    records = []
    for p in range(n_patients):
        for _ in range(int(rng.integers(1, 4))):
            group = ALL_DIR_NAMES[int(rng.integers(len(ALL_DIR_NAMES)))]
            label, severity = parse_dir_name(group)
            records.append(
                ManifestRecord(
                    image_path=f"{len(records):06d}.png",
                    patient_id=f"P{p:04d}",
                    label=label,
                    severity=severity,
                )
            )
    return records


def _prepared(config: ExperimentConfig, records: list[ManifestRecord]) -> list[PreparedFold]:
    position = {r.image_path: i for i, r in enumerate(records)}
    return [
        prepare_fold(
            fold,
            records,
            config,
            position,
            seed=fold_seed(config.split.seed, fold.index),
            log_prefix=f"fold{fold.index}",
        )
        for fold in make_kfold_splits(records, config.split.n_folds, config.split.seed)
    ]


def _patients_of(records: list[ManifestRecord], indices: np.ndarray) -> set[str]:
    return {records[int(i)].patient_id for i in indices}


@pytest.fixture(scope="module")
def records() -> list[ManifestRecord]:
    return _records()


@pytest.mark.parametrize("condition", CONDITIONS)
@pytest.mark.parametrize("stem", STEMS)
def test_split_is_the_same_as_the_existing_config(
    stem: str, condition: str, records: list[ManifestRecord]
) -> None:
    base = load_config(CONFIGS_DIR / f"cv_{condition}.yaml", environ={})
    config = load_config(PREDECESSOR_DIR / f"{stem}_{condition}.yaml", environ={})

    for ours, theirs in zip(_prepared(config, records), _prepared(base, records), strict=True):
        assert ours.train_patients == theirs.train_patients
        assert ours.val_patients == theirs.val_patients
        np.testing.assert_array_equal(ours.train_idx, theirs.train_idx)
        np.testing.assert_array_equal(ours.val_idx, theirs.val_idx)
        np.testing.assert_array_equal(ours.held_idx, theirs.held_idx)


@pytest.mark.parametrize("condition", CONDITIONS)
@pytest.mark.parametrize("stem", STEMS)
def test_patients_never_cross_train_val_held_out(
    stem: str, condition: str, records: list[ManifestRecord]
) -> None:
    config = load_config(PREDECESSOR_DIR / f"{stem}_{condition}.yaml", environ={})
    # 複数ラベルの患者がいる（このデータが検査として意味を持つこと）
    labels_of: dict[str, set[str]] = {}
    for r in records:
        labels_of.setdefault(r.patient_id, set()).add(r.label)
    assert any(len(labels) > 1 for labels in labels_of.values())

    held_seen: set[str] = set()
    for prepared in _prepared(config, records):
        train = _patients_of(records, prepared.train_idx)
        val = _patients_of(records, prepared.val_idx)
        held = _patients_of(records, prepared.held_idx)
        assert not train & val
        assert not train & held
        assert not val & held
        # 除外前の患者の一覧でも跨らない
        assert not set(prepared.train_patients) & set(prepared.val_patients)
        assert not set(prepared.train_patients) & held
        assert not set(prepared.val_patients) & held
        # 全 fold の held_out は重ならない
        assert not held_seen & held
        held_seen |= held
    assert held_seen == {r.patient_id for r in records}


def test_without_mild_is_a_subset_of_with_mild(records: list[ManifestRecord]) -> None:
    # 2 つの条件で同じ分割（SPEC_02「分割との関係」）．held_out はどちらも全程度
    with_mild = load_config(
        PREDECESSOR_DIR / "cv_pred_resnet34_color_shift_pseudo_only_with_mild.yaml", environ={}
    )
    without = load_config(
        PREDECESSOR_DIR / "cv_pred_resnet34_color_shift_pseudo_only_without_mild.yaml", environ={}
    )
    for a, b in zip(_prepared(with_mild, records), _prepared(without, records), strict=True):
        np.testing.assert_array_equal(a.held_idx, b.held_idx)
        assert set(b.train_idx.tolist()) <= set(a.train_idx.tolist())
        assert all(records[int(i)].severity != "mild" for i in b.train_idx)


# --- 疑似画像を入れても跨らない ---

SEED = 13
PER_GROUP = 9
IMAGE_SIZE = 16


class _StopError(Exception):
    """最初の fold の疑似画像を調べたら学習に入らずに打ち切る."""


def _write_dataset(root: Path) -> list[ManifestRecord]:
    # 各グループの先頭 2 枚は隣のグループと同じ患者にする（複数ラベルの患者）．
    rng = np.random.default_rng(0)
    records = []
    root.mkdir(parents=True, exist_ok=True)
    for g, group in enumerate(ALL_DIR_NAMES):
        label, severity = parse_dir_name(group)
        for i in range(PER_GROUP):
            name = f"{g}_{i}.png"
            color = rng.integers(40, 220, size=3)
            pixels = np.full((IMAGE_SIZE, IMAGE_SIZE, 3), color, dtype=np.uint8)
            pixels[:2, :2] = 0
            Image.fromarray(pixels).save(root / name)
            patient = f"M{i}{g // 3}" if i < 2 else f"P{g}{i}"
            records.append(
                ManifestRecord(image_path=name, patient_id=patient, label=label, severity=severity)
            )
    return records


def _config(root: Path, mode: str, severities: list[str]) -> ExperimentConfig:
    return ExperimentConfig.model_validate(
        {
            "data": {"root": str(root), "severities": severities},
            "split": {"seed": SEED, "n_folds": 3},
            "model": {"name": "resnet18", "pretrained": False},
            "train": {
                "image_size": IMAGE_SIZE,
                "batch_size": 4,
                "max_epochs": 1,
                "warmup_epochs": 0,
                "inner_val_ratio": 0.2,
                "num_workers": 0,
                "amp": False,
                "color_shift_pseudo": {"mode": mode},
            },
        }
    )


def _capture_first_fold(
    monkeypatch: pytest.MonkeyPatch,
    config: ExperimentConfig,
    records: list[ManifestRecord],
    images_dir: Path,
) -> dict:
    # run_cross_validation が疑似画像の生成に渡した入力と，その出力を取る．
    captured: dict = {}
    real = cv.make_pseudo_image_set

    def spy(images, labels, pseudo_config, *, seed):
        captured["images"] = images.copy()
        captured["labels"] = labels.copy()
        captured["seed"] = seed
        captured["result"] = real(images, labels, pseudo_config, seed=seed)
        raise _StopError

    monkeypatch.setattr(cv, "make_pseudo_image_set", spy)
    with pytest.raises(_StopError):
        run_cross_validation(config, records, images_dir, images_dir / "checkpoints")
    return captured


def _digest(image: np.ndarray) -> str:
    return hashlib.sha256(image.tobytes()).hexdigest()


def _first_fold(config: ExperimentConfig, records: list[ManifestRecord]) -> PreparedFold:
    return _prepared(config, records)[0]


@pytest.mark.parametrize("mode", ["real_plus_pseudo", "pseudo_only"])
@pytest.mark.parametrize(
    "severities", [["strong", "mild", "normal"], ["strong", "normal"]], ids=["with", "without"]
)
def test_pseudo_inputs_are_exactly_the_training_images(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str, severities: list[str]
) -> None:
    records = _write_dataset(tmp_path)
    config = _config(tmp_path, mode, severities)
    prepared = _first_fold(config, records)
    all_images = load_letterboxed_images(records, tmp_path, IMAGE_SIZE)

    captured = _capture_first_fold(monkeypatch, config, records, tmp_path)

    # data.severities 適用後の学習用の画像そのもの（検証用・held_out を含まない）
    np.testing.assert_array_equal(captured["images"], all_images[prepared.train_idx])
    assert captured["seed"] == fold_seed(SEED, 0)
    train_patients = _patients_of(records, prepared.train_idx)
    other_patients = _patients_of(records, prepared.val_idx) | _patients_of(
        records, prepared.held_idx
    )
    assert not train_patients & other_patients


@pytest.mark.parametrize("mode", ["real_plus_pseudo", "pseudo_only"])
def test_pseudo_sources_belong_to_training_patients(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str
) -> None:
    records = _write_dataset(tmp_path)
    config = _config(tmp_path, mode, ["strong", "mild", "normal"])
    prepared = _first_fold(config, records)

    result = _capture_first_fold(monkeypatch, config, records, tmp_path)["result"]

    assert len(result.source_indices) > 0
    # source_indices は学習用データの中の位置．manifest の位置に戻すと学習用の患者になる
    source_positions = prepared.train_idx[result.source_indices]
    assert _patients_of(records, source_positions) <= set(prepared.train_patients)
    held_and_val = _patients_of(records, prepared.val_idx) | _patients_of(
        records, prepared.held_idx
    )
    assert not _patients_of(records, source_positions) & held_and_val


def _repaint(root: Path, records: list[ManifestRecord], indices: np.ndarray) -> None:
    # 舌領域の色を極端な色に塗り替える（背景の黒はそのまま）．
    for i in indices:
        path = root / records[int(i)].image_path
        pixels = np.asarray(Image.open(path).convert("RGB")).copy()
        pixels[pixels.any(axis=2)] = (5, 250, 5)
        Image.fromarray(pixels).save(path)


@pytest.mark.parametrize("mode", ["real_plus_pseudo", "pseudo_only"])
def test_changing_val_and_held_out_does_not_change_pseudo_images(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str
) -> None:
    # 色統計に検証・テストのデータが混ざらない（変えても結果が 1 ビットも変わらない）
    records = _write_dataset(tmp_path)
    config = _config(tmp_path, mode, ["strong", "mild", "normal"])
    prepared = _first_fold(config, records)
    before = _capture_first_fold(monkeypatch, config, records, tmp_path)["result"]

    monkeypatch.undo()
    _repaint(tmp_path, records, np.concatenate([prepared.val_idx, prepared.held_idx]))
    after = _capture_first_fold(monkeypatch, config, records, tmp_path)["result"]

    np.testing.assert_array_equal(before.images, after.images)
    np.testing.assert_array_equal(before.labels, after.labels)
    np.testing.assert_array_equal(before.class_lab_mean, after.class_lab_mean)
    np.testing.assert_array_equal(before.class_lab_std, after.class_lab_std)


def test_changing_excluded_mild_training_images_does_not_change_pseudo_images(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    # 「ややあり除外」では学習側の mild も統計に入らない（data.severities 適用後から取る）
    records = _write_dataset(tmp_path)
    config = _config(tmp_path, "pseudo_only", ["strong", "normal"])
    prepared = _first_fold(config, records)
    before = _capture_first_fold(monkeypatch, config, records, tmp_path)["result"]

    monkeypatch.undo()
    mild_positions = np.array(
        [
            i
            for i, r in enumerate(records)
            if r.patient_id in set(prepared.train_patients) and r.severity == "mild"
        ]
    )
    assert len(mild_positions) > 0
    _repaint(tmp_path, records, mild_positions)
    after = _capture_first_fold(monkeypatch, config, records, tmp_path)["result"]

    np.testing.assert_array_equal(before.images, after.images)


def test_changing_training_images_does_change_pseudo_images(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    # 上のテストが空振りでないことの確認
    records = _write_dataset(tmp_path)
    config = _config(tmp_path, "pseudo_only", ["strong", "mild", "normal"])
    prepared = _first_fold(config, records)
    before = _capture_first_fold(monkeypatch, config, records, tmp_path)["result"]

    monkeypatch.undo()
    _repaint(tmp_path, records, prepared.train_idx[:3])
    after = _capture_first_fold(monkeypatch, config, records, tmp_path)["result"]

    assert not np.array_equal(before.class_lab_mean, after.class_lab_mean)


def test_mode_none_does_not_generate_pseudo_images(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    records = _write_dataset(tmp_path)
    config = _config(tmp_path, "none", ["strong", "mild", "normal"])

    def must_not_run(*args, **kwargs):
        raise AssertionError("mode: none で疑似画像を作った")

    monkeypatch.setattr(cv, "make_pseudo_image_set", must_not_run)

    # 学習が始まる直前で打ち切る（create_model に届けば疑似画像は作られなかった）
    def stop(*args, **kwargs):
        raise _StopError

    monkeypatch.setattr(cv, "create_model", stop)
    with pytest.raises(_StopError):
        run_cross_validation(config, records, tmp_path, tmp_path / "checkpoints")


def test_pseudo_images_do_not_duplicate_val_or_held_out_images(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    # real_plus_pseudo の実画像の部分に，検証用・held_out の画像が入らない
    records = _write_dataset(tmp_path)
    config = _config(tmp_path, "real_plus_pseudo", ["strong", "mild", "normal"])
    prepared = _first_fold(config, records)
    all_images = load_letterboxed_images(records, tmp_path, IMAGE_SIZE)
    result = _capture_first_fold(monkeypatch, config, records, tmp_path)["result"]

    others = {
        _digest(all_images[int(i)]) for i in np.concatenate([prepared.val_idx, prepared.held_idx])
    }
    assert not {_digest(image) for image in result.images} & others
