"""Dice＋BCE の損失（SPEC_02「損失」）.

原本: `legacy/source/losses.py` の `dice_loss`（ファイルに 2 回定義されているが同じ内容）と
`DiceCE`．既定（`bce_input="sigmoid"`）は原本どおりの計算である．
"""

from __future__ import annotations

import torch
from torch import nn

from tongue_seg_model.schema import BceInput, LossConfig


def dice_loss(pred: torch.Tensor, target: torch.Tensor, smooth: float = 1.0) -> torch.Tensor:
    """Dice 損失を計算する（原本: `legacy/source/losses.py` の `dice_loss`）.

    チャンネルごと・画像ごとに `1 − (2 × 積の和 ＋ smooth) / (予測の和 ＋ 正解の和 ＋ smooth)`
    を計算し（和は高さと幅の方向），全体を平均する．

    Args:
        pred: シグモイドを掛けた後の予測（`(B, C, H, W)`, float32, 値域 0.0〜1.0）．
        target: 正解（`(B, C, H, W)`, float32, 0 か 1．チャンネル 0 が舌）．
        smooth: 分母が 0 になるのを避ける値（原本は 1.0）．

    Returns:
        チャンネルごと・画像ごとの損失の平均（0 次元のテンソル）．
    """
    pred = pred.contiguous()
    target = target.contiguous()
    intersection = (pred * target).sum(dim=2).sum(dim=2)
    denominator = pred.sum(dim=2).sum(dim=2) + target.sum(dim=2).sum(dim=2) + smooth
    loss = 1 - ((2.0 * intersection + smooth) / denominator)
    return loss.mean()


class DiceBCELoss(nn.Module):
    """BCE と Dice の重み付き和の損失（原本: `legacy/source/losses.py` の `DiceCE`）.

    `損失 = bce_weight × BCE ＋ (1 − bce_weight) × Dice`．Dice には常に `sigmoid(出力)` を使う．
    BCE（`binary_cross_entropy_with_logits`，`reduction="mean"`）に渡す値は `bce_input` で
    切り替える．

    - `sigmoid`: `sigmoid(出力)` を渡す．シグモイドが 2 重に掛かる．**原本の挙動**．意図しない
      書き方と考えられるが，配布中の ONNX がこの損失で学習されたと考えられるため既定で残す
    - `logits`: モデルの出力をそのまま渡す（直した版）

    既定値は `schema.py` の `LossConfig` だけに置くため，引数に既定値を持たせない
    （`build_loss` から作る）．

    Args:
        bce_weight: BCE の重み（0〜1．Dice の重みは `1 − bce_weight`）．
        bce_input: BCE に渡す値（`sigmoid` / `logits`）．

    Raises:
        ValueError: `bce_input` が `sigmoid`・`logits` のどちらでもない場合．
    """

    def __init__(self, bce_weight: float, bce_input: BceInput) -> None:
        super().__init__()
        if bce_input not in ("sigmoid", "logits"):
            raise ValueError(f"bce_input は sigmoid か logits でなければならない: {bce_input!r}")
        self.bce_weight = bce_weight
        self.bce_input = bce_input

    def forward(self, output: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        """損失を計算する.

        Args:
            output: モデルの出力（`(B, 2, H, W)`, float32, 活性化関数を掛ける前の値）．
            target: 正解（`(B, 2, H, W)`, float32, 0 か 1．チャンネル 0 が舌）．

        Returns:
            損失（0 次元のテンソル）．
        """
        pred = torch.sigmoid(output)
        bce_source = pred if self.bce_input == "sigmoid" else output
        bce = nn.functional.binary_cross_entropy_with_logits(bce_source, target, reduction="mean")
        dice = dice_loss(pred, target)
        return (bce * self.bce_weight) + ((1.0 - self.bce_weight) * dice)


def build_loss(config: LossConfig) -> DiceBCELoss:
    """設定から損失を作る.

    Args:
        config: 損失の設定（`loss`）．

    Returns:
        設定どおりの `DiceBCELoss`．
    """
    return DiceBCELoss(bce_weight=config.bce_weight, bce_input=config.bce_input)
