"""乱数の固定（`training/reproducibility.py`）のテスト.

期待値は SPEC_02「学習」の乱数の固定の範囲（Python・NumPy・PyTorch の種と cuDNN の決定的な
動作．`torch.use_deterministic_algorithms` は有効にしない）を基準にする．
"""

from __future__ import annotations

import os
import random
from collections.abc import Iterator

import numpy as np
import pytest
import torch

from tongue_seg_model.training.reproducibility import fix_random_seed


@pytest.fixture(autouse=True)
def restore_global_state(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
    """cuDNN の設定と PYTHONHASHSEED を元に戻す（他のテストに影響させない）."""
    deterministic = torch.backends.cudnn.deterministic
    benchmark = torch.backends.cudnn.benchmark
    algorithms = torch.are_deterministic_algorithms_enabled()
    # monkeypatch に登録しておくと，テスト後に元の値（または未設定）に戻る
    monkeypatch.setenv("PYTHONHASHSEED", os.environ.get("PYTHONHASHSEED", "0"))
    yield
    torch.backends.cudnn.deterministic = deterministic
    torch.backends.cudnn.benchmark = benchmark
    torch.use_deterministic_algorithms(algorithms)


def _draw() -> tuple[float, float, list[float]]:
    return random.random(), float(np.random.rand()), torch.rand(3).tolist()


def test_same_seed_gives_same_random_numbers() -> None:
    fix_random_seed(2021)
    first = _draw()
    fix_random_seed(2021)
    second = _draw()
    assert first == second


def test_different_seed_gives_different_random_numbers() -> None:
    fix_random_seed(2021)
    first = _draw()
    fix_random_seed(2022)
    second = _draw()
    assert first[0] != second[0]
    assert first[1] != second[1]
    assert first[2] != second[2]


def test_sets_cudnn_flags_and_hash_seed() -> None:
    torch.backends.cudnn.deterministic = False
    torch.backends.cudnn.benchmark = True
    fix_random_seed(7)
    assert torch.backends.cudnn.deterministic is True
    assert torch.backends.cudnn.benchmark is False
    assert os.environ["PYTHONHASHSEED"] == "7"


def test_does_not_enable_deterministic_algorithms() -> None:
    fix_random_seed(0)
    assert torch.are_deterministic_algorithms_enabled() is False


def test_accepts_maximum_seed() -> None:
    fix_random_seed(2**32 - 1)
