"""Shared pacman queries mit Cache-Invalidation.

Zentral statt in jedem Pillar einen Subprocess-Call. Cache wird gecleart
nach jedem write-Aktion (install/remove)."""
from __future__ import annotations

import subprocess
from functools import lru_cache


@lru_cache(maxsize=1)
def installed_packages() -> frozenset[str]:
    try:
        r = subprocess.run(
            ["pacman", "-Qq"],
            capture_output=True, text=True, check=False, timeout=10,
        )
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return frozenset()
    return frozenset(l.strip() for l in r.stdout.splitlines() if l.strip())


def is_installed(name: str) -> bool:
    return name in installed_packages()


def invalidate() -> None:
    """Nach pacman -S/-R aufrufen."""
    installed_packages.cache_clear()
