"""学習の履歴 `history.csv` と学習曲線 `figures/loss.png`（`training/history.py`）のテスト.

期待値は SPEC_01「実験の出力」（`history.csv` はエポックごとの学習損失・検証損失，図は
`figures/loss.png`）と SPEC_02「学習」を基準にする．図は smoke テスト（ファイルが PNG として
できること）だけにする（testing.md「テストを必須としない対象」）．
"""

from __future__ import annotations

import csv
import io
import math
from pathlib import Path

from tongue_seg_model.training.history import (
    HISTORY_COLUMNS,
    HISTORY_FILENAME,
    LOSS_FIGURE_FILENAME,
    HistoryRow,
    history_csv_text,
    plot_loss_curve,
    write_history_csv,
)

PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"


def _rows() -> list[HistoryRow]:
    return [
        HistoryRow(epoch=1, train_loss=0.9, val_loss=0.8),
        HistoryRow(epoch=2, train_loss=0.7, val_loss=0.75),
        HistoryRow(epoch=3, train_loss=0.1 + 0.2, val_loss=1 / 3),
    ]


def _parse(text: str) -> list[dict[str, str]]:
    return list(csv.DictReader(io.StringIO(text)))


def test_names_match_spec01() -> None:
    assert HISTORY_FILENAME == "history.csv"
    assert LOSS_FIGURE_FILENAME == "loss.png"
    assert HISTORY_COLUMNS == ("epoch", "train_loss", "val_loss")


class TestHistoryCsvText:
    def test_header_and_rows(self) -> None:
        text = history_csv_text(_rows())
        lines = text.split("\n")
        assert lines[0] == "epoch,train_loss,val_loss"
        parsed = _parse(text)
        assert [row["epoch"] for row in parsed] == ["1", "2", "3"]

    def test_losses_round_trip_exactly(self) -> None:
        rows = _rows()
        parsed = _parse(history_csv_text(rows))
        for original, row in zip(rows, parsed, strict=True):
            assert float(row["train_loss"]) == original.train_loss
            assert float(row["val_loss"]) == original.val_loss

    def test_empty_history_is_header_only(self) -> None:
        assert history_csv_text([]) == "epoch,train_loss,val_loss\n"

    def test_uses_lf_line_endings(self) -> None:
        text = history_csv_text(_rows())
        assert "\r" not in text
        assert text.endswith("\n")
        assert text.count("\n") == 4

    def test_nan_loss_is_written_readably(self) -> None:
        text = history_csv_text([HistoryRow(epoch=1, train_loss=math.nan, val_loss=math.inf)])
        row = _parse(text)[0]
        assert math.isnan(float(row["train_loss"]))
        assert math.isinf(float(row["val_loss"]))


class TestWriteHistoryCsv:
    def test_writes_file(self, tmp_path: Path) -> None:
        path = write_history_csv(tmp_path / HISTORY_FILENAME, _rows())
        assert path == tmp_path / "history.csv"
        assert path.read_bytes() == history_csv_text(_rows()).encode("utf-8")

    def test_rewriting_replaces_whole_file(self, tmp_path: Path) -> None:
        path = tmp_path / HISTORY_FILENAME
        write_history_csv(path, _rows())
        write_history_csv(path, _rows()[:1])
        assert len(_parse(path.read_text(encoding="utf-8"))) == 1


class TestPlotLossCurve:
    def test_writes_png(self, tmp_path: Path) -> None:
        path = plot_loss_curve(tmp_path / LOSS_FIGURE_FILENAME, _rows())
        assert path == tmp_path / "loss.png"
        assert path.read_bytes().startswith(PNG_SIGNATURE)

    def test_single_epoch(self, tmp_path: Path) -> None:
        path = plot_loss_curve(tmp_path / "loss.png", _rows()[:1])
        assert path.read_bytes().startswith(PNG_SIGNATURE)
