"""Resolve CUDA devices by their stable hardware UUID, independent of index ordering."""

from __future__ import annotations

import re

import torch


def cuda_devices():
    """Return devices in PyTorch's logical CUDA order with their hardware identities."""
    devices = []
    for index in range(torch.cuda.device_count()):
        props = torch.cuda.get_device_properties(index)
        devices.append({"device": f"cuda:{index}", "cuda_index": index,
                        "uuid": str(getattr(props, "uuid", "") or ""),
                        "name": props.name, "total_memory_bytes": props.total_memory})
    return devices


def resolve_device(requested="cuda:0"):
    """Accept a CPU/CUDA index or full/unique-prefix GPU UUID and return torch.device."""
    if isinstance(requested, torch.device):
        requested = str(requested)
    requested = str(requested)
    if requested == "cpu":
        return torch.device("cpu")
    if requested == "cuda":
        requested = "cuda:0"
    match = re.fullmatch(r"(?:cuda:)?(?:GPU-)?([0-9a-fA-F-]{8,})", requested)
    if match:
        uuid = match.group(1).lower()
        matches = [item for item in cuda_devices()
                   if item["uuid"].lower().removeprefix("gpu-").startswith(uuid)]
        if len(matches) != 1:
            raise ValueError(f"GPU UUID {requested!r} matched {len(matches)} visible CUDA devices")
        return torch.device(matches[0]["device"])
    device = torch.device(requested)
    if device.type == "cuda":
        index = 0 if device.index is None else device.index
        if index >= torch.cuda.device_count():
            raise ValueError(f"CUDA device {requested!r} is not visible")
    return device


def device_metadata(requested="cuda:0"):
    """Describe the actual device selected by PyTorch."""
    device = resolve_device(requested)
    if device.type == "cpu":
        return {"device": "cpu", "name": "CPU", "uuid": None}
    index = 0 if device.index is None else device.index
    return cuda_devices()[index]


def pinned_cuda_metadata(requested):
    """Require the exact configured hardware UUID, even with a generic driver name."""
    match = re.fullmatch(r"(?:GPU-)?([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})", str(requested))
    if not match:
        raise ValueError("assistant training requires a full GPU UUID")
    metadata = device_metadata(requested)
    actual = str(metadata.get("uuid") or "").lower().removeprefix("gpu-")
    if actual != match.group(1).lower():
        raise ValueError("configured GPU UUID differs from the resolved hardware")
    return metadata
