"""Tests para cuda_available."""

import sys
import unittest
from unittest.mock import patch


# Asegurar que el modulo ml es importable desde el path del registry
sys.path.insert(0, "python/functions")

from ml.cuda_available import cuda_available


class TestCudaAvailable(unittest.TestCase):

    def test_claves_del_dict_siempre_presentes(self):
        """claves del dict siempre presentes"""
        result = cuda_available()
        for key in ("available", "device_count", "devices", "torch_version", "cuda_version"):
            self.assertIn(key, result, f"Falta clave: {key}")

    def test_sin_torch_retorna_available_False_y_torch_version_not_installed(self):
        """sin torch retorna available=False y torch_version=not_installed"""
        with patch.dict(sys.modules, {"torch": None}):
            result = cuda_available()
        self.assertFalse(result["available"])
        self.assertEqual(result["torch_version"], "not_installed")
        self.assertEqual(result["device_count"], 0)
        self.assertEqual(result["devices"], [])
        self.assertIsNone(result["cuda_version"])

    def test_con_torch_sin_cuda_retorna_available_False_y_device_count_0(self):
        """con torch sin cuda retorna available=False y device_count=0"""
        import types
        fake_torch = types.ModuleType("torch")
        fake_torch.__version__ = "2.3.0"
        fake_torch.cuda = types.SimpleNamespace(
            is_available=lambda: False,
            device_count=lambda: 0,
        )
        fake_torch.version = types.SimpleNamespace(cuda=None)

        with patch.dict(sys.modules, {"torch": fake_torch}):
            result = cuda_available()

        self.assertFalse(result["available"])
        self.assertEqual(result["device_count"], 0)
        self.assertEqual(result["devices"], [])
        self.assertEqual(result["torch_version"], "2.3.0")
        self.assertIsNone(result["cuda_version"])


if __name__ == "__main__":
    unittest.main()
