import logging
import os
import subprocess
from pathlib import Path

from .file_operations import read_file
from .hardware_parser import get_sysfs_path

logger = logging.getLogger(__name__)


def is_notebook() -> bool:
    """
    Returns True if dmidecode reports chassis type 'Notebook'.
    Equivalent to:
        dmidecode | grep -i 'type: notebook'
    """
    try:
        output = subprocess.check_output(
            ["dmidecode"], text=True, stderr=subprocess.DEVNULL
        )
        return "type: notebook" in output.lower()
    except Exception:
        logger.error("something went wrong during dmidecode")
        return False


def is_tuxedo_os() -> bool:
    """
    Returns True if the OS identifies as TUXEDO OS via /etc/os-release.
    Matches ID or ID_LIKE containing 'tuxedo'.
    """
    os_release = Path(os.environ.get("TUXEDO_OS_RELEASE", "/etc/os-release"))
    logger.debug("checking if TUXEDO OS through /etc/os-release")
    if not os_release.exists():
        logger.debug("no TUXEDO OS detected")
        return False

    try:
        lines = os_release.read_text(encoding="utf-8").splitlines()
        kv = dict(line.split("=", 1) for line in lines if "=" in line)
        os_id = kv.get("ID", "").strip('"').lower()
        os_like = kv.get("ID_LIKE", "").strip('"').lower()
        return os_id == "tuxedo" or "tuxedo" in os_like
    except Exception as e:
        logger.error(f"Exception occured during os detection: {e}")
        return False


def is_tuxedo_device() -> bool:
    """
    Returns True if ANY DMI field contains 'TUXEDO',
    or if board_name == 'P65_P67RGRERA'.
    Equivalent to FAI logic.
    """
    logger.debug("Checking for TUXEDO device through dmi strings")
    dmi_paths = {
        "SYSVENDOR": get_sysfs_path("/sys/devices/virtual/dmi/id/sys_vendor"),
        "CHASSISVENDOR": get_sysfs_path("/sys/devices/virtual/dmi/id/chassis_vendor"),
        "BOARDVENDOR": get_sysfs_path("/sys/devices/virtual/dmi/id/board_vendor"),
        "PRODUCTNAME": get_sysfs_path("/sys/devices/virtual/dmi/id/product_name"),
        "BOARDNAME": get_sysfs_path("/sys/devices/virtual/dmi/id/board_name"),
    }

    values = {key: read_file(path) for key, path in dmi_paths.items()}

    for val in values.values():
        if val and "tuxedo" in val.lower():
            logger.debug("TUXEDO found in dmi strings")
            return True

    # Legacy device with no tuxedo string
    if values.get("BOARDNAME") == "P65_P67RGRERA":
        logger.debug("Boardname P65_P67RGRERA detected, is tuxedo device")
        return True

    return False
