"""テスト全体で共有するフィクスチャ.

セグメンテーションのテスト（segmentation・evaluation・cli）で使うダミーの ONNX モデル
（`scripts/make_dummy_seg_models.py`．入出力の形だけを本物に合わせたもの）と，
合成データ生成スクリプト（`scripts/make_synthetic_segmentation.py`）の読み込み．
バンドルの読み込みのテスト（data・cli）で使う合成の TIASDataHub バンドルの書き出し．
"""

from __future__ import annotations

import importlib.util
import sys
from pathlib import Path
from types import ModuleType

import pytest

SCRIPTS_DIR = Path(__file__).resolve().parents[1] / "scripts"


def load_script(name: str) -> ModuleType:
    """`scripts/<name>.py` をモジュールとして読み込む."""
    module_name = f"_test_script_{name}"
    if module_name in sys.modules:
        return sys.modules[module_name]
    spec = importlib.util.spec_from_file_location(module_name, SCRIPTS_DIR / f"{name}.py")
    assert spec is not None and spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module


def write_tiasdata_bundle(bundles_dir: Path, items: list[dict], *, version: int = 1) -> Path:
    """`tiasdata` の書き出しと同じ形の合成バンドル `tongue_color/v<版>/` を作る.

    形の組み立てには `tiasdata` 自身の関数（`build_manifest` 等）を使い，形の食い違いを防ぐ．

    Args:
        bundles_dir: バンドルの置き場所（`TIASDATA_BUNDLES` に指定する）．
        items: 1 ファイルごとの dict（`data`: 中身のバイト列・`subject_id`・`label`・`severity`．
            任意で `kind`・`ext`．`label`・`severity` は None で空の欄になる）．
        version: 版．

    Returns:
        バンドルのフォルダ．
    """
    import hashlib

    from tiasdata.bundle import BUNDLE_FORMAT, BundleInfo, build_dataset_json, build_sha256sums
    from tiasdata.manifest import ManifestEntry, build_manifest, manifest_sha256

    root = bundles_dir / "tongue_color" / f"v{version}"
    (root / "files").mkdir(parents=True)
    entries = []
    for n, item in enumerate(items):
        sha256 = hashlib.sha256(item["data"]).hexdigest()
        ext = item.get("ext", "png")
        (root / "files" / f"{sha256}.{ext}").write_bytes(item["data"])
        entries.append(
            ManifestEntry(
                sha256=sha256,
                ext=ext,
                kind=item.get("kind", "tongue_crop_masked"),
                subject_id=item["subject_id"],
                capture_id=f"C{n:04d}",
                annotations={
                    "tongue_color": {"label": item["label"], "severity": item["severity"]}
                },
            )
        )
    manifest = build_manifest(entries, {"tongue_color": ["label", "severity"]})
    (root / "manifest.csv").write_bytes(manifest)
    (root / "SHA256SUMS").write_bytes(
        build_sha256sums((e.sha256, f"files/{e.sha256}.{e.ext}") for e in entries)
    )
    info = BundleInfo(
        format=BUNDLE_FORMAT,
        name="tongue_color",
        version=version,
        created_at="2026-10-01T00:00:00Z",
        hub_commit="0000000",
        files=len(entries),
        manifest_sha256=manifest_sha256(manifest),
    )
    (root / "dataset.json").write_bytes(build_dataset_json(info))
    return root


def synthetic_bundle_items(
    work_dir: Path, *, per_dir: int, secret: str = "SECRETSUBJ", seed: int = 0
) -> list[dict]:
    """合成データの画像から，複数ラベルの患者を含むバンドルの中身を作る.

    各グループの先頭 2 枚は，隣り合う 3 グループ（例: 淡白の 2 グループと淡紅）で同じ患者にする．

    Args:
        work_dir: 合成データの作業ディレクトリ（存在しないこと）．
        per_dir: グループごとの枚数．
        secret: 患者 ID に入れる目印（出力に紛れ込んでいないか検索するため）．
        seed: 合成データの seed．

    Returns:
        `write_tiasdata_bundle` の `items`．
    """
    from tias_judge_model.data.classes import ALL_DIR_NAMES, parse_dir_name

    load_script("make_synthetic_dataset").generate(work_dir, per_dir=per_dir, seed=seed)
    items = []
    for g, group in enumerate(ALL_DIR_NAMES):
        label, severity = parse_dir_name(group)
        for i, png in enumerate(sorted((work_dir / "images" / group).glob("*.png"))):
            subject = f"{secret}M{i}{g // 3}" if i < 2 else f"{secret}{g}{i:03d}"
            items.append(
                {
                    "data": png.read_bytes(),
                    "subject_id": subject,
                    "label": label,
                    "severity": severity,
                }
            )
    return items


@pytest.fixture(scope="session")
def dummy_seg_models(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Path]:
    """ダミーの ResUNet・検出モデルの ONNX を書き出し，そのパスを返す."""
    onnx = pytest.importorskip("onnx")
    script = load_script("make_dummy_seg_models")
    out = tmp_path_factory.mktemp("dummy_seg_models")
    onnx.save(script.build_resunet(), out / "ResUNet.onnx")
    onnx.save(script.build_detector(), out / "Detection_Normal.onnx")
    return {
        "root": out,
        "resunet": out / "ResUNet.onnx",
        "detector": out / "Detection_Normal.onnx",
    }


@pytest.fixture(scope="session")
def script_loader():
    """`scripts/<name>.py` を読み込む関数（`load_script`）を返す."""
    return load_script


@pytest.fixture(scope="session")
def bundle_writer():
    """合成バンドルを書き出す関数（`write_tiasdata_bundle`）を返す."""
    return write_tiasdata_bundle


@pytest.fixture(scope="session")
def bundle_items():
    """合成データからバンドルの中身を作る関数（`synthetic_bundle_items`）を返す."""
    return synthetic_bundle_items
