"""GPU runtime helpers."""

from __future__ import annotations

import os
from pathlib import Path

_DLL_HANDLES: list[object] = []
_CONFIGURED = False


def configure_nvidia_dll_path() -> None:
    """Expose NVIDIA wheel DLL directories to the Windows dynamic loader.

    Paddle's Windows GPU wheels dynamically load CUDA/cuDNN DLLs by name. When
    those DLLs come from Python packages such as ``nvidia-cudnn-cu11`` instead
    of a system-wide CUDA Toolkit install, their ``bin`` folders are not on
    ``PATH`` by default.
    """
    global _CONFIGURED
    if _CONFIGURED or os.name != "nt":
        return

    package_names = ("nvidia.cudnn", "nvidia.cublas", "nvidia.cuda_nvrtc")
    dll_dirs: list[Path] = []
    for package_name in package_names:
        try:
            module = __import__(package_name, fromlist=["__file__"])
        except Exception:
            continue
        module_file = getattr(module, "__file__", None)
        if not module_file:
            continue
        dll_dir = Path(module_file).resolve().parent / "bin"
        if dll_dir.is_dir():
            dll_dirs.append(dll_dir)

    if not dll_dirs:
        _CONFIGURED = True
        return

    current_path_parts = os.environ.get("PATH", "").split(os.pathsep)
    current_path_norm = {part.casefold() for part in current_path_parts if part}

    prepend: list[str] = []
    for dll_dir in dll_dirs:
        dll_dir_str = str(dll_dir)
        if dll_dir_str.casefold() not in current_path_norm:
            prepend.append(dll_dir_str)
        add_dll_directory = getattr(os, "add_dll_directory", None)
        if add_dll_directory is not None:
            _DLL_HANDLES.append(add_dll_directory(dll_dir_str))

    if prepend:
        os.environ["PATH"] = os.pathsep.join([*prepend, os.environ.get("PATH", "")])

    _CONFIGURED = True
