"""学習の結果の記録 `metrics.json` と画像ごとの IoU `predictions.csv`（SPEC_01「実験の出力」）.

- `metrics.json`（回収する）: 集計値だけを書く（最良エポック・最良の検証損失・テスト用データでの
  IoU の集計値・件数・バンドルの指紋）．画像ごとの値・ファイル名・患者 ID は書かない
- `predictions.csv`（回収しない）: テスト用データの画像ごとの IoU．組は画像の行の manifest の
  行番号（`split.json` と同じ識別）で表し，パス・ID は書かない

原本: `legacy/source/main.py` の `Log.txt`（全体平均）と `Log_detail.csv`（画像のファイル名と
IoU）．原本の `Log_detail.csv` は画像のファイル名を含んでいたが，ここでは行番号にする．
内容の組み立ては純関数，書き出しは縁の関数である．
"""

from __future__ import annotations

import csv
import io
import json
import math
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any

METRICS_FILENAME = "metrics.json"
"""集計値のファイル名（回収する）．"""
PREDICTIONS_FILENAME = "predictions.csv"
"""画像ごとの IoU のファイル名（回収しない．SPEC_01「回収ホワイトリスト」）．"""

PREDICTION_COLUMNS: tuple[str, ...] = ("image_line", "iou")
"""`predictions.csv` の列．"""


def build_metrics_document(
    *,
    best_epoch: int,
    best_val_loss: float,
    epochs_run: int,
    stopped_early: bool,
    test_iou: Mapping[str, int | float],
    counts: Mapping[str, int],
    data_bundle: Mapping[str, str | int],
    elapsed_seconds: float,
) -> dict[str, Any]:
    """`metrics.json` に書く内容を作る（純関数）.

    Args:
        best_epoch: 検証損失が最良だったエポック（1 から数える）．
        best_val_loss: 最良の検証損失．
        epochs_run: 実際に回したエポック数．
        stopped_early: 早期終了で止まったか（最大エポック数より前に止まったか）．
        test_iou: テスト用データでの IoU の集計値（`summarize_ious` の戻り値）．
        counts: 学習用・検証用・テスト用の組の数（`train`・`val`・`test`）．
        data_bundle: バンドルの指紋（`BundleFingerprint.to_dict` の戻り値）．
        elapsed_seconds: 学習と評価にかかった時間（秒）．

    Returns:
        JSON に書き出せる dict．
    """
    return {
        "best_epoch": best_epoch,
        "best_val_loss": best_val_loss,
        "epochs_run": epochs_run,
        "stopped_early": stopped_early,
        "test_iou": dict(test_iou),
        "counts": dict(counts),
        "data_bundle": dict(data_bundle),
        "elapsed_seconds": elapsed_seconds,
    }


def json_safe(value: Any) -> Any:
    """NaN・無限大を None に置き換える（純関数）.

    Python の `json` は NaN・無限大を `NaN`・`Infinity` と書き，厳密な JSON でなくなる
    （他の言語・ツールで読めない）．損失が発散した実験でも `metrics.json` を読めるように，
    有限でない値は `null` にする．

    Args:
        value: JSON に書く値（dict・list・tuple は中までたどる）．

    Returns:
        有限でない float を None に置き換えた値．dict・list は新しく作る（tuple は list になる）．
    """
    if isinstance(value, float) and not math.isfinite(value):
        return None
    if isinstance(value, Mapping):
        return {key: json_safe(item) for key, item in value.items()}
    if isinstance(value, list | tuple):
        return [json_safe(item) for item in value]
    return value


def write_metrics_json(path: Path, document: Mapping[str, Any]) -> Path:
    """`metrics.json` を書き出す.

    有限でない値（NaN・無限大）は `null` と書く（`json_safe`）．

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

    Returns:
        書き出したパス．
    """
    text = json.dumps(json_safe(document), ensure_ascii=False, indent=2, allow_nan=False) + "\n"
    path.write_text(text, encoding="utf-8", newline="")
    return path


def predictions_csv_text(image_lines: Sequence[int], ious: Sequence[float]) -> str:
    """`predictions.csv` の中身を作る（純関数）.

    Args:
        image_lines: テスト用の組の画像の行の manifest の行番号（評価した順）．
        ious: 同じ順の画像ごとの IoU．

    Returns:
        見出し行付きの CSV の文字列（改行は LF）．

    Raises:
        RuntimeError: 行番号と IoU の数が一致しない場合（内部の誤り）．
    """
    if len(image_lines) != len(ious):
        raise RuntimeError(f"行番号の数 {len(image_lines)} と IoU の数 {len(ious)} が一致しない")
    buffer = io.StringIO()
    writer = csv.writer(buffer, lineterminator="\n")
    writer.writerow(PREDICTION_COLUMNS)
    for line, iou in zip(image_lines, ious, strict=True):
        writer.writerow([line, repr(float(iou))])
    return buffer.getvalue()


def write_predictions_csv(path: Path, image_lines: Sequence[int], ious: Sequence[float]) -> Path:
    """`predictions.csv` を書き出す.

    Args:
        path: 書き出す先（`runs/<実験ID>/predictions.csv`）．
        image_lines: テスト用の組の画像の行の manifest の行番号．
        ious: 同じ順の画像ごとの IoU．

    Returns:
        書き出したパス．
    """
    path.write_text(predictions_csv_text(image_lines, ious), encoding="utf-8", newline="")
    return path
