"""学習ループと学習後の評価（`training/loop.py`）のテスト.

期待値は SPEC_02「学習」（損失はバッチごとの損失の平均・検証損失が最良を更新したエポックの重みを
`checkpoints/best.pth` に上書き・`early_stopping_patience` エポック続けて更新しなければ止める）と
「学習後の評価」（1 枚ずつ シグモイド → 255 倍 → 大津の 2 値化 → IoU）を基準にする．

早期終了の挙動は，検証のときだけ決めた値を返す損失を使って確かめる（学習の数値に依存しない）．
モデルは 1×1 の畳み込みだけの小さなものにする．
"""

from __future__ import annotations

import math
from collections.abc import Iterator, Sequence
from pathlib import Path

import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

from tongue_seg_model.training.history import HistoryRow
from tongue_seg_model.training.loop import fit, predict_ious, run_epoch

CPU = torch.device("cpu")
SIZE = 8


def _loader(n: int, batch_size: int, seed: int = 0) -> DataLoader:
    generator = torch.Generator().manual_seed(seed)
    images = torch.rand(n, 3, SIZE, SIZE, generator=generator)
    labels = (torch.rand(n, 1, SIZE, SIZE, generator=generator) > 0.5).float()
    labels = torch.cat([labels, 1 - labels], dim=1)
    return DataLoader(TensorDataset(images, labels), batch_size=batch_size, shuffle=False)


def _model(seed: int = 0) -> nn.Module:
    torch.manual_seed(seed)
    return nn.Conv2d(3, 2, kernel_size=1)


class ScriptedValLoss(nn.Module):
    """学習のときは本物の損失，検証のときは決めた値を順に返す損失."""

    def __init__(self, model: nn.Module, val_losses: Sequence[float]) -> None:
        super().__init__()
        self._model = model
        self._val: Iterator[float] = iter(val_losses)
        self.train_calls = 0
        self.val_calls = 0

    def forward(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
        if self._model.training:
            self.train_calls += 1
            return nn.functional.binary_cross_entropy_with_logits(outputs, labels)
        self.val_calls += 1
        return outputs.sum() * 0 + next(self._val)


def _fit(
    tmp_path: Path,
    val_losses: Sequence[float],
    *,
    max_epochs: int,
    patience: int,
    snapshots: list[dict[str, torch.Tensor]] | None = None,
    calls: list[tuple[HistoryRow, ...]] | None = None,
):
    model = _model()
    criterion = ScriptedValLoss(model, val_losses)
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)

    def on_epoch(rows: Sequence[HistoryRow]) -> None:
        if calls is not None:
            calls.append(tuple(rows))
        if snapshots is not None:
            snapshots.append({k: v.detach().clone() for k, v in model.state_dict().items()})

    result = fit(
        model,
        train_loader=_loader(4, 2),
        val_loader=_loader(2, 2, seed=1),  # 1 バッチ → 検証損失は決めた値そのもの
        criterion=criterion,
        optimizer=optimizer,
        device=CPU,
        max_epochs=max_epochs,
        patience=patience,
        checkpoint_path=tmp_path / "best.pth",
        on_epoch=on_epoch,
    )
    return result, model


# ---------------------------------------------------------------------------
# run_epoch
# ---------------------------------------------------------------------------


class ConstantPerBatchLoss(nn.Module):
    """バッチごとに決めた値を返す損失（勾配はモデルの出力につなぐ）."""

    def __init__(self, values: Sequence[float]) -> None:
        super().__init__()
        self._values = iter(values)

    def forward(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
        return (outputs - labels).pow(2).mean() * 0 + next(self._values)


class TestRunEpoch:
    def test_returns_unweighted_mean_of_batch_losses(self) -> None:
        # 3 件をバッチの大きさ 2 で回すと 2 件・1 件のバッチになる．平均は件数で重み付けしない
        loss = run_epoch(_model(), _loader(3, 2), ConstantPerBatchLoss([1.0, 4.0]), CPU)
        assert loss == pytest.approx(2.5)

    def test_validation_does_not_change_weights_and_uses_eval_mode(self) -> None:
        model = _model()
        before = {k: v.clone() for k, v in model.state_dict().items()}
        seen: list[tuple[bool, bool]] = []

        class Recording(nn.Module):
            def forward(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
                seen.append((model.training, torch.is_grad_enabled()))
                return nn.functional.binary_cross_entropy_with_logits(outputs, labels)

        run_epoch(model, _loader(4, 2), Recording(), CPU)
        assert seen == [(False, False), (False, False)]
        for key, value in model.state_dict().items():
            assert torch.equal(value, before[key])

    def test_training_updates_weights_and_uses_train_mode(self) -> None:
        model = _model()
        model.eval()
        before = {k: v.clone() for k, v in model.state_dict().items()}
        seen: list[bool] = []

        class Recording(nn.Module):
            def forward(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
                seen.append(model.training)
                return nn.functional.binary_cross_entropy_with_logits(outputs, labels)

        optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
        run_epoch(model, _loader(4, 2), Recording(), CPU, optimizer)
        assert seen == [True, True]
        assert not torch.equal(model.weight, before["weight"])


# ---------------------------------------------------------------------------
# fit（早期終了・最良の重みの保存）
# ---------------------------------------------------------------------------


class TestFitEarlyStopping:
    def test_stops_after_patience_epochs_without_improvement(self, tmp_path: Path) -> None:
        result, _ = _fit(tmp_path, [0.9, 0.5, 0.6, 0.7, 0.4, 0.3], max_epochs=6, patience=2)
        assert [row.epoch for row in result.history] == [1, 2, 3, 4]
        assert result.best_epoch == 2
        assert result.best_val_loss == pytest.approx(0.5)
        assert result.stopped_early is True

    def test_runs_all_epochs_while_improving(self, tmp_path: Path) -> None:
        result, _ = _fit(tmp_path, [0.9, 0.8, 0.7], max_epochs=3, patience=1)
        assert len(result.history) == 3
        assert result.best_epoch == 3
        assert result.stopped_early is False

    def test_stop_condition_on_last_epoch_is_not_early(self, tmp_path: Path) -> None:
        # 3 エポック目で止める条件を満たすが，最大エポック数なので「早期終了」ではない
        result, _ = _fit(tmp_path, [0.5, 0.6, 0.7], max_epochs=3, patience=2)
        assert len(result.history) == 3
        assert result.best_epoch == 1
        assert result.stopped_early is False

    def test_equal_loss_does_not_count_as_improvement(self, tmp_path: Path) -> None:
        result, _ = _fit(tmp_path, [0.5, 0.5, 0.5, 0.5], max_epochs=4, patience=2)
        assert result.best_epoch == 1
        assert len(result.history) == 3
        assert result.stopped_early is True

    def test_history_records_train_and_scripted_val_losses(self, tmp_path: Path) -> None:
        result, _ = _fit(tmp_path, [0.9, 0.8], max_epochs=2, patience=5)
        assert [row.val_loss for row in result.history] == pytest.approx([0.9, 0.8])
        assert all(math.isfinite(row.train_loss) for row in result.history)

    def test_on_epoch_receives_history_so_far(self, tmp_path: Path) -> None:
        calls: list[tuple[HistoryRow, ...]] = []
        result, _ = _fit(tmp_path, [0.9, 0.8, 0.85], max_epochs=3, patience=5, calls=calls)
        assert [len(c) for c in calls] == [1, 2, 3]
        assert [row.epoch for row in calls[-1]] == [1, 2, 3]
        assert calls[-1] == result.history

    def test_all_nan_validation_raises(self, tmp_path: Path) -> None:
        with pytest.raises(ValueError):
            _fit(tmp_path, [math.nan] * 5, max_epochs=5, patience=2)
        assert not (tmp_path / "best.pth").exists()

    def test_nan_then_finite_is_ok(self, tmp_path: Path) -> None:
        result, _ = _fit(tmp_path, [math.nan, 0.7, 0.8], max_epochs=3, patience=5)
        assert result.best_epoch == 2


class TestFitCheckpoint:
    def test_best_pth_holds_weights_of_best_epoch(self, tmp_path: Path) -> None:
        snapshots: list[dict[str, torch.Tensor]] = []
        result, model = _fit(
            tmp_path, [0.9, 0.5, 0.6, 0.7], max_epochs=4, patience=5, snapshots=snapshots
        )
        assert result.best_epoch == 2
        saved = torch.load(tmp_path / "best.pth", weights_only=True)
        best = snapshots[result.best_epoch - 1]
        assert set(saved) == set(best)
        for key in best:
            assert torch.equal(saved[key], best[key])
        # 最後のエポックの重みとは違う（最良のものだけが残る）
        assert not torch.equal(saved["weight"], model.state_dict()["weight"])

    def test_checkpoint_is_overwritten_not_multiplied(self, tmp_path: Path) -> None:
        _fit(tmp_path, [0.9, 0.8, 0.7], max_epochs=3, patience=5)
        assert sorted(p.name for p in tmp_path.iterdir()) == ["best.pth"]

    def test_checkpoint_loads_into_same_model(self, tmp_path: Path) -> None:
        _fit(tmp_path, [0.9, 0.8], max_epochs=2, patience=5)
        fresh = _model(seed=123)
        fresh.load_state_dict(torch.load(tmp_path / "best.pth", weights_only=True))


# ---------------------------------------------------------------------------
# predict_ious
# ---------------------------------------------------------------------------


class PassThroughLogits(nn.Module):
    """入力の先頭 2 チャンネルをそのまま出力にするモデル（予測を入力で決めるため）."""

    def __init__(self) -> None:
        super().__init__()
        self.dummy = nn.Parameter(torch.zeros(1))
        self.modes: list[bool] = []

    def forward(self, inputs: torch.Tensor) -> torch.Tensor:
        self.modes.append(self.training)
        return inputs[:, :2] + self.dummy * 0


def _case(pred_rows: int, true_rows: int) -> tuple[torch.Tensor, torch.Tensor]:
    """上から `pred_rows` 行を舌と予測し，上から `true_rows` 行が正解の舌である 1 枚."""
    image = torch.full((3, SIZE, SIZE), -10.0)
    image[0, :pred_rows] = 10.0
    label = torch.zeros(2, SIZE, SIZE)
    label[0, :true_rows] = 1.0
    label[1] = 1 - label[0]
    return image, label


def test_predict_ious_per_image_in_loader_order() -> None:
    cases = [_case(4, 2), _case(4, 4), _case(2, 4), _case(4, 8)]
    images = torch.stack([c[0] for c in cases])
    labels = torch.stack([c[1] for c in cases])
    loader = DataLoader(TensorDataset(images, labels), batch_size=3, shuffle=False)
    model = PassThroughLogits()
    ious = predict_ious(model, loader, CPU)
    assert ious == pytest.approx([0.5, 1.0, 0.5, 0.5])
    assert all(isinstance(v, float) for v in ious)
    assert model.modes == [False, False]


def test_predict_ious_uniformly_negative_output_gives_zero() -> None:
    # 一様に十分小さい出力（8 ビットで全画素 0）は 2 値化で全画素 0 になり，正解に舌があれば
    # IoU は 0．※ 出力 0（全画素 127）のような 0 でない一様な値では，今の OpenCV の大津の
    # 2 値化はしきい値 0 を返して全画素 255 になる（SPEC_02 の記述と合わない．報告済み）
    image = torch.full((1, 3, SIZE, SIZE), -20.0)
    _, label = _case(0, 4)
    loader = DataLoader(TensorDataset(image, label.unsqueeze(0)), batch_size=1)
    assert predict_ious(PassThroughLogits(), loader, CPU) == [0.0]
