import logging
from functools import cache
from pathlib import Path

from test_automation_suite.utility.cmd import run_cmd

logger = logging.getLogger(__name__)


@cache
def is_notebook() -> bool:
    chassis_type_file = Path("/sys/class/dmi/id/chassis_type")

    if chassis_type_file.exists():
        with chassis_type_file.open() as f:
            chassis_type = f.read().strip()
            return int(chassis_type) in (8, 9, 10, 14, 15, 16, 17)

    return False


@cache
def get_gpu_vendors_list() -> list[str]:
    drm_path = Path("/sys/class/drm")
    if not drm_path.exists():
        logger.error("no /sys/class/drm found")
        return []

    vendors = set()

    for entry in drm_path.iterdir():
        # only real cards
        if entry.name.startswith("card") and not entry.name.startswith("card-DP"):
            device_path = drm_path / entry / "device" / "vendor"
            if device_path.exists():
                try:
                    with device_path.open() as f:
                        vendor_id = f.read().strip()
                        vendors.add(vendor_id)
                except Exception:
                    continue

    return list(vendors)


def has_nvidia_gpu() -> bool:
    # NVIDIA = 0x10de
    return "0x10de" in get_gpu_vendors_list()


def has_only_nvidia_gpu() -> bool:
    # NVIDIA = 0x10de
    return get_gpu_vendors_list() == ["0x10de"]


@cache
def check_prime_mode() -> str | None:
    result = run_cmd("prime-select query")
    if not result.success:
        logger.error("Failed to query prime mode: %s", result.stderr)
        return None
    return result.stdout.strip()


@cache
def check_which_prime_select() -> bool:
    return run_cmd("which prime-select").success
