# common/os_utils.py
import platform
import os
from functools import lru_cache


# Map distro IDs (from /etc/os-release) to (fontawesome_class, display_name)
_DISTRO_MAPPING = {
    'debian': ('fa-brands fa-debian', 'Debian'),
    'ubuntu': ('fa-brands fa-ubuntu', 'Ubuntu'),
    'fedora': ('fa-brands fa-fedora', 'Fedora'),
    'rhel': ('fa-brands fa-redhat', 'RHEL'),
    'centos': ('fa-brands fa-centos', 'CentOS'),
    'opensuse': ('fa-brands fa-opensuse', 'openSUSE'),
    'suse': ('fa-brands fa-suse', 'SUSE'),
    'arch': ('fa-brands fa-arch-linux', 'Arch Linux'),
    'raspbian': ('fa-brands fa-raspberry-pi', 'Raspberry Pi OS'),
}

# Map platform.system() values to (fontawesome_class, display_name)
_SYSTEM_MAPPING = {
    'Windows': ('fa-brands fa-windows', 'Windows'),
    'Darwin': ('fa-brands fa-apple', 'macOS'),
    'FreeBSD': ('fa-brands fa-freebsd', 'FreeBSD'),
}


def _parse_os_release():
    """
    Read /etc/os-release and return (distro_id, distro_name, id_like_list).
    Any missing field falls back to empty values.
    """
    distro_id = ''
    distro_name = ''
    id_like = ''
    try:
        with open('/etc/os-release', 'r') as f:
            for line in f:
                if line.startswith('ID='):
                    distro_id = line.split('=', 1)[1].strip().strip('"').lower()
                elif line.startswith('NAME='):
                    distro_name = line.split('=', 1)[1].strip().strip('"')
                elif line.startswith('ID_LIKE='):
                    id_like = line.split('=', 1)[1].strip().strip('"')
    except Exception:
        pass
    return distro_id, distro_name, id_like.split()


@lru_cache(maxsize=1)
def get_os_info():
    """
    Detect the operating system / Linux distribution and return
    (fontawesome_class, display_name). Falls back to generic Linux.
    """
    system = platform.system()
    if system != 'Linux':
        return _SYSTEM_MAPPING.get(system, ('fa-brands fa-linux', system))

    distro_id, distro_name, id_like = _parse_os_release()

    # Exact ID match first
    if distro_id in _DISTRO_MAPPING:
        return _DISTRO_MAPPING[distro_id]

    # ID_LIKE fallback (e.g. linuxmint/pop/neon -> ubuntu, lmde/kali -> debian,
    # rocky/almalinux -> rhel/fedora). Walk in order and take the first hit.
    for parent in id_like:
        if parent in _DISTRO_MAPPING:
            return _DISTRO_MAPPING[parent]

    return ('fa-brands fa-linux', distro_name or 'Linux')