"""計算装置の決定（`training/device.py`）のテスト.

期待値は SPEC_02「設定項目」の `train.device`（`auto`＝GPU があれば使い無ければ CPU・`cpu`・
`cuda`・`cuda:<番号>`）を基準にする．GPU の有無は引数で渡す（実際の GPU に依存しない）．
"""

from __future__ import annotations

import pytest
import torch

from tongue_seg_model.training.device import resolve_device, select_device


class TestResolveDevice:
    def test_auto_uses_gpu_when_available(self) -> None:
        assert resolve_device("auto", cuda_available=True, cuda_device_count=2) == "cuda"

    def test_auto_falls_back_to_cpu_without_gpu(self) -> None:
        assert resolve_device("auto", cuda_available=False, cuda_device_count=0) == "cpu"

    @pytest.mark.parametrize("available", [True, False])
    def test_cpu_is_always_cpu(self, available: bool) -> None:
        count = 1 if available else 0
        assert resolve_device("cpu", cuda_available=available, cuda_device_count=count) == "cpu"

    def test_cuda_with_gpu(self) -> None:
        assert resolve_device("cuda", cuda_available=True, cuda_device_count=1) == "cuda"

    @pytest.mark.parametrize("spec", ["cuda", "cuda:0", "cuda:3"])
    def test_gpu_requested_without_gpu_raises(self, spec: str) -> None:
        with pytest.raises(ValueError):
            resolve_device(spec, cuda_available=False, cuda_device_count=0)

    @pytest.mark.parametrize(("spec", "count"), [("cuda:0", 1), ("cuda:1", 2), ("cuda:3", 4)])
    def test_cuda_index_within_count(self, spec: str, count: int) -> None:
        assert resolve_device(spec, cuda_available=True, cuda_device_count=count) == spec

    @pytest.mark.parametrize(("spec", "count"), [("cuda:1", 1), ("cuda:2", 2), ("cuda:7", 4)])
    def test_cuda_index_out_of_range_raises(self, spec: str, count: int) -> None:
        with pytest.raises(ValueError):
            resolve_device(spec, cuda_available=True, cuda_device_count=count)


def test_select_device_cpu_returns_torch_device() -> None:
    assert select_device("cpu") == torch.device("cpu")


def test_select_device_auto_matches_environment() -> None:
    expected = "cuda" if torch.cuda.is_available() else "cpu"
    assert select_device("auto").type == expected


@pytest.mark.skipif(torch.cuda.is_available(), reason="GPU が無い環境でだけ確かめる")
def test_select_device_cuda_without_gpu_raises() -> None:
    with pytest.raises(ValueError):
        select_device("cuda")
