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

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

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

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
