"""合成バンドルの生成スクリプトのテスト（ENV_04「合成バンドルの生成」）.

- 実データと別の名前（`tongue_color_synthetic`）で作る．手元用の設定をサーバで動かしても実データを
  読まない
- `tiasdata.load` で読めて照合が通る．版 3 と同じ形（DeepTIAS の特徴量の 15 列つき）
- 複数ラベルの患者を含む
- 苔のしきい値で舌本体が空にならない（SPEC_02 の 2 組のしきい値）
- 同じ seed で同じ内容．`--overwrite` は目印のある出力先だけを消す
- `--first-round`: 実データと別の名前（`tongue_color_first_round_synthetic`）の版 1 を別の出力先に
  作る．所見 `tongue_color_first_round` と，1 クラスずらして一部を空にした `tongue_color` の列つき
"""

from __future__ import annotations

from pathlib import Path
from types import ModuleType

import numpy as np
import pytest
import tiasdata
from PIL import Image

from tias_judge_model.data.bundle import deeptias_feature_matrix, load_dataset_source
from tias_judge_model.data.classes import CLASS_SLUGS
from tias_judge_model.data.coat_features import tongue_body_mask
from tias_judge_model.schema import CoatRemovalConfig, DataConfig, load_config

REAL_BUNDLE_NAME = "tongue_color"
SYNTHETIC_NAME = "tongue_color_synthetic"
PER_DIR = 4


@pytest.fixture(scope="module")
def script(script_loader) -> ModuleType:
    return script_loader("make_synthetic_bundle")


@pytest.fixture(scope="module")
def bundles(script: ModuleType, tmp_path_factory: pytest.TempPathFactory) -> Path:
    out = tmp_path_factory.mktemp("bundles") / "out"
    assert script.main(["--out", str(out), "--per-dir", str(PER_DIR), "--seed", "0"]) == 0
    return out


@pytest.fixture
def source(bundles: Path, monkeypatch: pytest.MonkeyPatch):
    monkeypatch.setenv("TIASDATA_BUNDLES", str(bundles))
    return load_dataset_source(
        DataConfig.model_validate({"bundle": {"name": SYNTHETIC_NAME, "version": 3}})
    )


def test_default_name_is_not_the_real_bundle(script: ModuleType, bundles: Path) -> None:
    assert script.DEFAULT_NAME == SYNTHETIC_NAME
    assert SYNTHETIC_NAME != REAL_BUNDLE_NAME
    assert (bundles / SYNTHETIC_NAME / "v3").is_dir()
    assert not (bundles / REAL_BUNDLE_NAME).exists()


def test_real_bundle_name_cannot_be_loaded_from_synthetic_bundles(
    bundles: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.setenv("TIASDATA_BUNDLES", str(bundles))
    with pytest.raises(ValueError):
        tiasdata.load(REAL_BUNDLE_NAME, version=3)


def test_bundle_loads_and_verifies(bundles: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("TIASDATA_BUNDLES", str(bundles))
    bundle = tiasdata.load(SYNTHETIC_NAME, version=3)
    bundle.verify()
    assert bundle.name == SYNTHETIC_NAME
    assert bundle.version == 3
    assert len(bundle.rows) == 9 * PER_DIR


def test_records_have_all_classes_and_multi_label_patients(source) -> None:
    assert {r.label for r in source.records} == set(CLASS_SLUGS)
    assert {r.severity for r in source.records} == {"strong", "mild", "normal"}
    labels_by_patient: dict[str, set[str]] = {}
    for r in source.records:
        labels_by_patient.setdefault(r.patient_id, set()).add(r.label)
    assert any(len(labels) > 1 for labels in labels_by_patient.values())


def test_deeptias_columns_are_readable(source) -> None:
    matrix = deeptias_feature_matrix(source)
    assert matrix.shape == (9 * PER_DIR, 15)
    assert np.isfinite(matrix).all()


@pytest.mark.parametrize(
    "thresholds",
    [
        pytest.param(
            {
                "white": {"h": [0, 180], "s": [0, 92], "v": [0, 255]},
                "yellow": {"h": [0, 89], "s": [0, 255], "v": [0, 255]},
            },
            id="final_code",
        ),
        pytest.param(
            {
                "white": {"h": [0, 180], "s": [0, 80], "v": [0, 255]},
                "yellow": {"h": [0, 20], "s": [0, 255], "v": [0, 255]},
            },
            id="slide",
        ),
    ],
)
def test_coat_removal_leaves_tongue_body(source, thresholds: dict) -> None:
    config = CoatRemovalConfig.model_validate(thresholds)
    for record in source.records:
        with Image.open(source.images_dir / record.image_path) as image:
            pixels = np.asarray(image.convert("RGB"))
        assert (pixels == 0).all(axis=2).any()  # 背景は黒
        body = tongue_body_mask(pixels, config)
        assert body.any()
        # 舌苔の代わりの領域が実際に除かれている
        assert body.sum() < pixels.any(axis=2).sum()


def _snapshot(root: Path) -> dict[str, bytes]:
    return {p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()}


def test_same_seed_is_reproducible(script: ModuleType, tmp_path: Path) -> None:
    assert script.main(["--out", str(tmp_path / "a"), "--per-dir", "2", "--seed", "5"]) == 0
    assert script.main(["--out", str(tmp_path / "b"), "--per-dir", "2", "--seed", "5"]) == 0
    assert _snapshot(tmp_path / "a") == _snapshot(tmp_path / "b")


def test_refuses_non_empty_output_without_overwrite(script: ModuleType, tmp_path: Path) -> None:
    out = tmp_path / "out"
    assert script.main(["--out", str(out), "--per-dir", "1"]) == 0
    before = _snapshot(out)
    assert script.main(["--out", str(out), "--per-dir", "1"]) == 1
    assert _snapshot(out) == before


def test_overwrite_removes_only_marked_output(script: ModuleType, tmp_path: Path) -> None:
    out = tmp_path / "real"
    out.mkdir()
    (out / "precious.txt").write_text("keep", encoding="utf-8")
    assert script.main(["--out", str(out), "--per-dir", "1", "--overwrite"]) == 1
    assert (out / "precious.txt").read_text(encoding="utf-8") == "keep"


def test_overwrite_regenerates_marked_output(script: ModuleType, tmp_path: Path) -> None:
    out = tmp_path / "out"
    assert script.main(["--out", str(out), "--per-dir", "1", "--seed", "0"]) == 0
    assert script.main(["--out", str(out), "--per-dir", "2", "--seed", "1", "--overwrite"]) == 0
    assert len(tiasdata.open_bundle(out / SYNTHETIC_NAME / "v3").rows) == 9 * 2


# --- --first-round（ENV_04「合成バンドルの生成（1 回目のラベル）」・SPEC_02） ---

# 1 グループ 5 枚目以降で tongue_color が空の行が出るので，それより多くする
FIRST_ROUND_PER_DIR = 6
FIRST_ROUND_NAME = "tongue_color_first_round_synthetic"
REAL_FIRST_ROUND_NAME = "tongue_color_first_round"
FIRST_ROUND_KIND = "tongue_color_first_round"
CONFIGS_DIR = Path(__file__).resolve().parents[2] / "configs"


@pytest.fixture(scope="module")
def first_round_bundles(script: ModuleType, tmp_path_factory: pytest.TempPathFactory) -> Path:
    out = tmp_path_factory.mktemp("first_round") / "out"
    args = [
        "--first-round",
        "--out",
        str(out),
        "--per-dir",
        str(FIRST_ROUND_PER_DIR),
        "--seed",
        "0",
    ]
    assert script.main(args) == 0
    return out


@pytest.fixture
def first_round_bundle(first_round_bundles: Path, monkeypatch: pytest.MonkeyPatch):
    monkeypatch.setenv("TIASDATA_BUNDLES", str(first_round_bundles))
    return tiasdata.load(FIRST_ROUND_NAME, version=1)


def _first_round_data(label_kind: str = FIRST_ROUND_KIND) -> DataConfig:
    return DataConfig.model_validate(
        {"bundle": {"name": FIRST_ROUND_NAME, "version": 1, "label_kind": label_kind}}
    )


def test_first_round_name_and_version(script: ModuleType, first_round_bundles: Path) -> None:
    assert FIRST_ROUND_NAME != REAL_FIRST_ROUND_NAME
    assert (first_round_bundles / FIRST_ROUND_NAME / "v1").is_dir()
    assert not (first_round_bundles / REAL_FIRST_ROUND_NAME).exists()
    assert not (first_round_bundles / SYNTHETIC_NAME).exists()


def test_first_round_real_name_cannot_be_loaded(
    first_round_bundles: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.setenv("TIASDATA_BUNDLES", str(first_round_bundles))
    with pytest.raises(ValueError):
        tiasdata.load(REAL_FIRST_ROUND_NAME, version=1)


def test_first_round_bundle_loads_and_verifies(first_round_bundle) -> None:
    first_round_bundle.verify()
    assert first_round_bundle.name == FIRST_ROUND_NAME
    assert first_round_bundle.version == 1
    assert len(first_round_bundle.rows) == 9 * FIRST_ROUND_PER_DIR


def test_first_round_levels_are_the_manifest_strings(first_round_bundle) -> None:
    rows = first_round_bundle.rows
    levels = [row.annotations[FIRST_ROUND_KIND]["level"] for row in rows]
    assert set(levels) == {"1", "2", "3"}  # strong は 2 と 3 の両方が出る
    for row in rows:
        annotation = row.annotations[FIRST_ROUND_KIND]
        if annotation["label"] == "light_red":
            assert annotation["level"] == "1"


def test_first_round_tongue_color_is_shifted_and_partly_empty(first_round_bundle) -> None:
    empty = 0
    for row in first_round_bundle.rows:
        new_label = row.annotations.get("tongue_color", {}).get("label")
        if new_label is None:
            empty += 1
        else:
            # 誤ってこちらを読むと結果が変わる
            assert new_label != row.annotations[FIRST_ROUND_KIND]["label"]
    assert 0 < empty < len(first_round_bundle.rows)


def test_first_round_records_cover_all_groups(first_round_bundles, monkeypatch) -> None:
    monkeypatch.setenv("TIASDATA_BUNDLES", str(first_round_bundles))
    records = load_dataset_source(_first_round_data()).records
    assert len(records) == 9 * FIRST_ROUND_PER_DIR
    counts: dict[tuple[str, str], int] = {}
    for record in records:
        key = (record.label, record.severity)
        counts[key] = counts.get(key, 0) + 1
    expected = {("light_red", "normal"): FIRST_ROUND_PER_DIR}
    for label in set(CLASS_SLUGS) - {"light_red"}:
        expected[(label, "strong")] = FIRST_ROUND_PER_DIR
        expected[(label, "mild")] = FIRST_ROUND_PER_DIR
    assert counts == expected
    labels_by_patient: dict[str, set[str]] = {}
    for record in records:
        labels_by_patient.setdefault(record.patient_id, set()).add(record.label)
    assert any(len(labels) > 1 for labels in labels_by_patient.values())


def test_first_round_records_are_converted_from_level(first_round_bundle, monkeypatch) -> None:
    # 読み込みの全経路（設定 → バンドル → レコード）で，tongue_color でなく level から作る
    source = load_dataset_source(_first_round_data())
    for row, record in zip(first_round_bundle.rows, source.records, strict=True):
        annotation = row.annotations[FIRST_ROUND_KIND]
        assert record.label == annotation["label"]
        if annotation["label"] == "light_red":
            assert record.severity == "normal"
        else:
            assert record.severity == ("mild" if annotation["level"] == "1" else "strong")


def test_first_round_bundle_stops_with_default_label_kind(first_round_bundle) -> None:
    # 既定の label_kind では空の tongue_color で今までどおり止まる
    with pytest.raises(ValueError, match="tongue_color の label が空"):
        load_dataset_source(_first_round_data("tongue_color"))


def test_first_round_deeptias_columns_are_readable(first_round_bundle) -> None:
    matrix = deeptias_feature_matrix(load_dataset_source(_first_round_data()))
    assert matrix.shape == (9 * FIRST_ROUND_PER_DIR, 15)
    assert np.isfinite(matrix).all()


def test_default_bundle_has_no_first_round_column(bundles: Path) -> None:
    manifest = (bundles / SYNTHETIC_NAME / "v3" / "manifest.csv").read_text(encoding="utf-8")
    assert "first_round" not in manifest
    assert "level" not in manifest.splitlines()[0]


def test_first_round_same_seed_is_reproducible(script: ModuleType, tmp_path: Path) -> None:
    for name in ("a", "b"):
        args = ["--first-round", "--out", str(tmp_path / name), "--per-dir", "2", "--seed", "5"]
        assert script.main(args) == 0
    assert _snapshot(tmp_path / "a") == _snapshot(tmp_path / "b")


def test_default_output_directories_are_separate(
    script: ModuleType, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    # --overwrite は出力先全体を消す．既定の出力先が別なので，互いを巻き込まない
    monkeypatch.chdir(tmp_path)
    assert script.main(["--per-dir", "1"]) == 0
    assert script.main(["--first-round", "--per-dir", "1"]) == 0
    v3 = tmp_path / "data" / "synthetic_bundles" / SYNTHETIC_NAME / "v3"
    v1 = tmp_path / "data" / "synthetic_bundles_first_round" / FIRST_ROUND_NAME / "v1"
    assert v3.is_dir()
    assert v1.is_dir()

    before = _snapshot(v3)
    assert script.main(["--first-round", "--per-dir", "2", "--overwrite"]) == 0
    assert _snapshot(v3) == before
    assert len(tiasdata.open_bundle(v1).rows) == 9 * 2


def test_first_round_refuses_non_empty_output_without_overwrite(
    script: ModuleType, tmp_path: Path
) -> None:
    out = tmp_path / "out"
    assert script.main(["--first-round", "--out", str(out), "--per-dir", "1"]) == 0
    before = _snapshot(out)
    assert script.main(["--first-round", "--out", str(out), "--per-dir", "1"]) == 1
    assert _snapshot(out) == before


@pytest.mark.parametrize(
    "path",
    sorted((CONFIGS_DIR / "predecessor_first_round" / "synthetic").glob("*.yaml")),
    ids=lambda p: p.stem,
)
def test_first_round_synthetic_configs_read_the_generated_bundle(
    path: Path, first_round_bundles: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.setenv("TIASDATA_BUNDLES", str(first_round_bundles))
    config = load_config(path, environ={})
    assert len(load_dataset_source(config.data).records) == 9 * FIRST_ROUND_PER_DIR
