"""Paket-Zähler — pacman + flatpak. UI-frei.

Schnelle Counts fürs Dashboard. pacman-Queries sind billig; flatpak kann etwas
dauern, daher im Aufrufer am besten async laden.
"""
from __future__ import annotations

import shutil
import subprocess

from taninux.core.pacman import installed_packages


def _count(args: list[str], timeout: int = 8) -> int:
    try:
        r = subprocess.run(args, capture_output=True, text=True,
                           check=False, timeout=timeout)
        if r.returncode != 0:
            return 0
        return sum(1 for line in r.stdout.splitlines() if line.strip())
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return 0


def pacman_total() -> int:
    return len(installed_packages())


def pacman_explicit() -> int:
    return _count(["pacman", "-Qeq"])


def pacman_foreign() -> int:
    """AUR / nicht-Repo-Pakete."""
    return _count(["pacman", "-Qmq"])


def flatpak_installed() -> bool:
    return shutil.which("flatpak") is not None


def flatpak_apps() -> int:
    """Anzahl installierter Flatpak-Apps; -1 wenn flatpak fehlt."""
    if not flatpak_installed():
        return -1
    return _count(["flatpak", "list", "--app", "--columns=application"])
