from __future__ import annotations

import os
import pwd
import shutil
from dataclasses import dataclass
from pathlib import Path


@dataclass(frozen=True)
class SystemInfo:
    distro_id: str
    pretty_name: str
    package_manager: str
    target_user: str
    target_home: Path
    target_uid: int
    target_gid: int


def _read_os_release() -> dict[str, str]:
    values: dict[str, str] = {}
    release_file = Path("/etc/os-release")
    if not release_file.exists():
        return values

    for line in release_file.read_text(encoding="utf-8").splitlines():
        if "=" not in line or line.startswith("#"):
            continue
        key, value = line.split("=", 1)
        values[key] = value.strip().strip('"')
    return values


def detect_package_manager() -> str:
    for candidate in ("apt-get", "dnf", "yum", "pacman"):
        if shutil.which(candidate):
            return candidate
    return "unknown"


def resolve_target_user() -> tuple[str, Path, int, int]:
    user_name = os.environ.get("SUDO_USER") or os.environ.get("USER") or "root"
    user_info = pwd.getpwnam(user_name)
    return user_name, Path(user_info.pw_dir), user_info.pw_uid, user_info.pw_gid


def detect_system() -> SystemInfo:
    values = _read_os_release()
    package_manager = detect_package_manager()
    user_name, user_home, uid, gid = resolve_target_user()
    return SystemInfo(
        distro_id=values.get("ID", "unknown"),
        pretty_name=values.get("PRETTY_NAME", "Linux"),
        package_manager=package_manager,
        target_user=user_name,
        target_home=user_home,
        target_uid=uid,
        target_gid=gid,
    )
