"""
GPU Utilities - CUDA detection and device management

Torch is optional - if not installed, defaults to CPU.
"""

# Try to import torch, but don't fail if not installed
try:
    import torch
    TORCH_AVAILABLE = True
except ImportError:
    TORCH_AVAILABLE = False


def get_device() -> str:
    """Get best available device (CUDA or CPU)."""
    if TORCH_AVAILABLE and torch.cuda.is_available():
        return 'cuda'
    return 'cpu'


def get_gpu_info() -> dict:
    """Get GPU information if available."""
    if not TORCH_AVAILABLE or not torch.cuda.is_available():
        return {
            "available": False,
            "device": "cpu",
            "name": None,
            "memory_gb": None
        }

    return {
        "available": True,
        "device": "cuda",
        "name": torch.cuda.get_device_name(0),
        "memory_gb": round(torch.cuda.get_device_properties(0).total_memory / 1e9, 2)
    }


def clear_gpu_memory():
    """Clear GPU memory cache."""
    if TORCH_AVAILABLE and torch.cuda.is_available():
        torch.cuda.empty_cache()


# Quick test
if __name__ == "__main__":
    print(f"Torch available: {TORCH_AVAILABLE}")
    print(f"Device: {get_device()}")
    print(f"GPU Info: {get_gpu_info()}")
