"""学習用と検証用の分割と，分割結果の記録 `split.json`（SPEC_02「分割」・SPEC_01「実験の出力」）.

原本: `legacy/source/main.py` の
`random_split(dataset, [int(n * train_ratio), n - int(n * train_ratio)])`
（画像単位．端数は検証側）．

並べ替えは seed から作った専用の乱数生成器（`torch.Generator`）で行い，グローバルな乱数の状態に
依存しない（同じ seed・同じ入力なら同じ結果）．原本の `random_split` は `fix_rand(seed)` 直後の
既定の生成器で `torch.randperm(n)` を引くので，画像単位の分割は同じ並べ替えの手順になる．
"""

from __future__ import annotations

import json
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import torch

from tongue_seg_model.data.bundle import SUBSET_TEST, SUBSET_TRAIN, SegRecord
from tongue_seg_model.schema import SplitMethod

SPLIT_FILENAME = "split.json"
"""分割結果のファイル名（回収しない．SPEC_01「回収ホワイトリスト」）．"""


@dataclass(frozen=True)
class SplitResult:
    """学習用と検証用の分割の結果.

    Attributes:
        train: 学習用の組．
        val: 検証用の組．
    """

    train: tuple[SegRecord, ...]
    val: tuple[SegRecord, ...]


def train_count(n: int, train_ratio: float) -> int:
    """学習用の件数 `int(n × train_ratio)` を返す（原本の `random_split` と同じ．端数は検証側）.

    Args:
        n: 分割する件数．
        train_ratio: 学習用の割合（0〜1 の開区間）．

    Returns:
        学習用の件数（切り捨て）．
    """
    return int(n * train_ratio)


def _permutation(n: int, seed: int) -> list[int]:
    generator = torch.Generator().manual_seed(seed)
    return torch.randperm(n, generator=generator).tolist()


def _split_random(records: Sequence[SegRecord], train_ratio: float, seed: int) -> SplitResult:
    n_train = train_count(len(records), train_ratio)
    order = _permutation(len(records), seed)
    return SplitResult(
        train=tuple(records[i] for i in order[:n_train]),
        val=tuple(records[i] for i in order[n_train:]),
    )


def _split_subject(records: Sequence[SegRecord], train_ratio: float, seed: int) -> SplitResult:
    empty = sum(1 for record in records if not record.subject_id)
    if empty:
        raise ValueError(
            f"患者単位の分割（data.split: subject）には患者の ID が要るが，subject_id が空の組が"
            f" {empty} 件ある"
        )
    groups: dict[str, list[SegRecord]] = {}
    for record in records:
        groups.setdefault(record.subject_id, []).append(record)
    if len(groups) < 2:
        raise ValueError(
            f"患者単位の分割には 2 人以上の患者が要る"
            f"（subset: {SUBSET_TRAIN} の患者 {len(groups)} 人）"
        )
    # 並べ替えの前の順を入力の順に依存させないため，患者の ID の順にそろえる．
    subjects = sorted(groups)
    target = train_count(len(records), train_ratio)
    train: list[SegRecord] = []
    val: list[SegRecord] = []
    for i in _permutation(len(subjects), seed):
        members = groups[subjects[i]]
        if len(train) + len(members) <= target:
            train.extend(members)
        else:
            val.extend(members)
    return SplitResult(train=tuple(train), val=tuple(val))


def split_records(
    records: Sequence[SegRecord], method: SplitMethod, train_ratio: float, seed: int
) -> SplitResult:
    """`subset` が `train` の組を学習用と検証用に分ける（純関数）.

    `subset` が `test` の組は対象外（無視する）．

    - `random`（原本どおり．画像単位）: seed の専用の生成器で `torch.randperm(n)` を引き，先頭
      `int(n × train_ratio)` 件を学習用，残りを検証用にする．各側の順は並べ替えた順
    - `subject`（患者単位）: 患者の ID を文字列の順に並べ，seed の専用の生成器で
      `torch.randperm(患者数)` を引いた順に患者を見ていく．その患者の組をすべて足しても学習用が
      `int(n × train_ratio)` 件を超えなければ学習用に，超えるなら検証用に入れる（後ろの小さい
      患者で埋められるので，学習用の件数は目標以下で目標に近くなる）．同じ患者の組は学習と検証に
      またがらない．患者の中の組は入力の順

    Args:
        records: 組の列（`load_seg_bundle` の `records`．`test` を含んでよい）．
        method: 分け方（`data.split`）．
        train_ratio: 学習用の割合（`data.train_ratio`．0〜1 の開区間）．
        seed: 乱数の種（`train.seed`）．

    Returns:
        学習用と検証用の組．

    Raises:
        ValueError: 学習用か検証用が空になる，`subject` で `subject_id` が空の組がある，
            または `subject` で患者が 2 人未満の場合．
    """
    train_records = [record for record in records if record.subset == SUBSET_TRAIN]
    if method == "random":
        result = _split_random(train_records, train_ratio, seed)
    elif method == "subject":
        result = _split_subject(train_records, train_ratio, seed)
    else:
        raise ValueError(f"分割の方法 {method!r} は使えない（random・subject のどちらか）")
    if not result.train or not result.val:
        raise ValueError(
            f"分割（{method}）で学習用か検証用が空になる（subset: {SUBSET_TRAIN} の組 "
            f"{len(train_records)} 件．学習用 {len(result.train)} 件・検証用 {len(result.val)} 件．"
            "組を増やすか data.train_ratio を見直す）"
        )
    return result


def build_split_document(
    split: SplitResult,
    records: Sequence[SegRecord],
    *,
    method: SplitMethod,
    seed: int,
    train_ratio: float,
    bundle: Mapping[str, str | int] | None = None,
) -> dict[str, Any]:
    """`split.json` に書く内容を作る（純関数）.

    各組は画像の行の manifest の行番号（見出しが 1 行目）で識別する（`capture_id`・パスは
    入れない．`split.json` は回収しないが，行番号があればサーバ上で特定できる）．

    Args:
        split: `split_records` の結果．
        records: 組の列全体（`subset` が `test` の組を数えて並べるために使う）．
        method: 分け方．
        seed: 乱数の種．
        train_ratio: 学習用の割合．
        bundle: バンドルの指紋（`name`・`version`・`manifest_sha256`）．None なら null．

    Returns:
        `{"method", "seed", "train_ratio", "bundle", "counts": {"train", "val", "test"},
        "image_lines": {"train", "val", "test"}}` の dict．`image_lines` の各リストは行番号の
        昇順．
    """
    test = [record for record in records if record.subset == SUBSET_TEST]
    groups = {"train": split.train, "val": split.val, "test": test}
    return {
        "method": method,
        "seed": seed,
        "train_ratio": train_ratio,
        "bundle": None if bundle is None else dict(bundle),
        "counts": {name: len(group) for name, group in groups.items()},
        "image_lines": {
            name: sorted(record.image_line for record in group) for name, group in groups.items()
        },
    }


def write_split_json(path: Path, document: Mapping[str, Any]) -> Path:
    """`split.json` を書き出す（既にあれば上書きせずに止める）.

    Args:
        path: 書き出す先（`runs/<実験ID>/split.json`）．
        document: `build_split_document` の戻り値．

    Returns:
        書き出したパス．

    Raises:
        ValueError: 既にファイルがある場合．
    """
    text = json.dumps(document, ensure_ascii=False, indent=2) + "\n"
    try:
        with path.open("x", encoding="utf-8", newline="\n") as f:
            f.write(text)
    except FileExistsError:
        raise ValueError(f"{SPLIT_FILENAME} が既にある（上書きしない）") from None
    return path
