"""`metrics.json` と `predictions.csv`（`training/metrics.py`）のテスト.

期待値は SPEC_01「実験の出力」（`metrics.json` は最良エポック・最良の検証損失・テスト用データでの
IoU の集計値・バンドルの指紋．`predictions.csv` は画像ごとの IoU で回収しない）と SPEC_02
「学習後の評価」（`metrics.json` には集計値だけを書き，画像ごとの値は `predictions.csv` に書く）を
基準にする．組は画像の行の manifest の行番号で表し，ファイル名・パス・ID を書かない．
"""

from __future__ import annotations

import csv
import io
import json
import math
from pathlib import Path
from typing import Any

import pytest

from tongue_seg_model.training.metrics import (
    METRICS_FILENAME,
    PREDICTION_COLUMNS,
    PREDICTIONS_FILENAME,
    build_metrics_document,
    json_safe,
    predictions_csv_text,
    write_metrics_json,
    write_predictions_csv,
)

SHA = "0123456789abcdef" * 4
TEST_IOU = {"count": 3, "mean": 0.5, "median": 0.4, "min": 0.1, "max": 1.0, "std": 0.3}
COUNTS = {"train": 8, "val": 4, "test": 3}
BUNDLE = {"name": "synthetic", "version": 1, "manifest_sha256": SHA}


def _document(**overrides: Any) -> dict[str, Any]:
    kwargs: dict[str, Any] = {
        "best_epoch": 2,
        "best_val_loss": 0.25,
        "epochs_run": 5,
        "stopped_early": True,
        "test_iou": TEST_IOU,
        "counts": COUNTS,
        "data_bundle": BUNDLE,
        "elapsed_seconds": 12.5,
    }
    kwargs.update(overrides)
    return build_metrics_document(**kwargs)


def _strict_loads(text: str) -> Any:
    def _reject(constant: str) -> Any:
        raise AssertionError(f"厳密な JSON でない値 {constant} がある")

    return json.loads(text, parse_constant=_reject)


def test_names_match_spec01() -> None:
    assert METRICS_FILENAME == "metrics.json"
    assert PREDICTIONS_FILENAME == "predictions.csv"
    assert PREDICTION_COLUMNS == ("image_line", "iou")


class TestBuildMetricsDocument:
    def test_has_exactly_the_spec_keys(self) -> None:
        doc = _document()
        assert set(doc) == {
            "best_epoch",
            "best_val_loss",
            "epochs_run",
            "stopped_early",
            "test_iou",
            "counts",
            "data_bundle",
            "elapsed_seconds",
        }

    def test_values(self) -> None:
        doc = _document()
        assert doc["best_epoch"] == 2
        assert doc["best_val_loss"] == 0.25
        assert doc["epochs_run"] == 5
        assert doc["stopped_early"] is True
        assert doc["test_iou"] == TEST_IOU
        assert doc["counts"] == COUNTS
        assert doc["data_bundle"] == BUNDLE
        assert doc["elapsed_seconds"] == 12.5

    def test_copies_nested_mappings(self) -> None:
        test_iou = dict(TEST_IOU)
        doc = _document(test_iou=test_iou)
        test_iou["mean"] = 0.0
        assert doc["test_iou"]["mean"] == 0.5

    def test_contains_no_per_image_values(self) -> None:
        # 集計値だけ（画像ごとの値の列が入らない）
        doc = _document()
        for value in doc["test_iou"].values():
            assert isinstance(value, int | float)


class TestJsonSafe:
    @pytest.mark.parametrize("value", [math.nan, math.inf, -math.inf])
    def test_non_finite_float_becomes_none(self, value: float) -> None:
        assert json_safe(value) is None

    @pytest.mark.parametrize("value", [0.0, 1.5, -2.0, 3, True, "NaN", None])
    def test_other_values_unchanged(self, value: Any) -> None:
        assert json_safe(value) == value
        assert type(json_safe(value)) is type(value)

    def test_nested_structures(self) -> None:
        value = {"a": [1.0, math.nan, (math.inf, 2)], "b": {"c": -math.inf, "d": "x"}}
        assert json_safe(value) == {"a": [1.0, None, [None, 2]], "b": {"c": None, "d": "x"}}

    def test_does_not_modify_input(self) -> None:
        value = {"a": [math.nan]}
        json_safe(value)
        assert math.isnan(value["a"][0])


class TestWriteMetricsJson:
    def test_round_trips(self, tmp_path: Path) -> None:
        doc = _document()
        path = write_metrics_json(tmp_path / METRICS_FILENAME, doc)
        assert path == tmp_path / "metrics.json"
        assert _strict_loads(path.read_text(encoding="utf-8")) == doc

    def test_non_finite_values_are_null(self, tmp_path: Path) -> None:
        doc = _document(
            best_val_loss=math.nan,
            test_iou={**TEST_IOU, "std": math.inf},
        )
        path = write_metrics_json(tmp_path / METRICS_FILENAME, doc)
        loaded = _strict_loads(path.read_text(encoding="utf-8"))
        assert loaded["best_val_loss"] is None
        assert loaded["test_iou"]["std"] is None
        assert loaded["test_iou"]["mean"] == 0.5


class TestPredictionsCsvText:
    def test_header_and_rows(self) -> None:
        text = predictions_csv_text([2, 4, 10], [0.5, 1.0, 0.0])
        assert text == "image_line,iou\n2,0.5\n4,1.0\n10,0.0\n"

    def test_iou_round_trips_exactly(self) -> None:
        ious = [1 / 3, 0.1 + 0.2]
        rows = list(csv.DictReader(io.StringIO(predictions_csv_text([3, 5], ious))))
        assert [float(r["iou"]) for r in rows] == ious
        assert [int(r["image_line"]) for r in rows] == [3, 5]

    def test_accepts_numpy_floats(self) -> None:
        np = pytest.importorskip("numpy")
        text = predictions_csv_text([2], [np.float32(0.5)])
        assert text == "image_line,iou\n2,0.5\n"

    def test_empty(self) -> None:
        assert predictions_csv_text([], []) == "image_line,iou\n"

    def test_length_mismatch_raises(self) -> None:
        with pytest.raises(RuntimeError):
            predictions_csv_text([2, 3], [0.5])

    def test_has_only_line_number_and_iou_columns(self) -> None:
        rows = list(csv.reader(io.StringIO(predictions_csv_text([2], [0.5]))))
        assert all(len(row) == 2 for row in rows)


def test_write_predictions_csv(tmp_path: Path) -> None:
    path = write_predictions_csv(tmp_path / PREDICTIONS_FILENAME, [2, 4], [0.25, 0.75])
    assert path == tmp_path / "predictions.csv"
    assert path.read_bytes() == b"image_line,iou\n2,0.25\n4,0.75\n"
