"""CPU / CuPy / dpnp device 名を個別に確認する補助関数。"""

from __future__ import annotations

import platform
from pathlib import Path


def get_cpu_name() -> str:
    """CPU model name を返す。Linux/WSL では /proc/cpuinfo を優先する。"""
    cpuinfo = Path("/proc/cpuinfo")

    if cpuinfo.exists():
        try:
            for line in cpuinfo.read_text(
                encoding="utf-8", errors="ignore"
            ).splitlines():
                if line.lower().startswith("model name"):
                    return line.split(":", 1)[1].strip()
        except Exception:
            pass

    name = platform.processor().strip()
    if name:
        return name

    return platform.machine().strip() or "Unknown CPU"


def get_cupy_device_name(device_id: int = 0) -> str:
    """CuPy device 名を返す。利用不能なら説明文字列を返す。"""
    try:
        import cupy as cp
        props = cp.cuda.runtime.getDeviceProperties(device_id)
        name = props["name"]
        if isinstance(name, bytes):
            name = name.decode(errors="replace")
        return str(name)
    except Exception as exc:
        return f"CuPy device unavailable: {exc}"


def get_dpnp_device_name(device: str = "gpu") -> str:
    """dpnp/dpctl から SYCL device 名を返す。"""
    try:
        import dpctl
        queue = dpctl.SyclQueue(device)
        return str(queue.sycl_device.name)
    except Exception as exc:
        return f"SYCL device unavailable: {exc}"
