"""Sudo-Helper: Password-Cache via `sudo -v`."""
from __future__ import annotations

import subprocess


def is_cached() -> bool:
    """Prüft ob sudo-credentials noch im 5-min cache stehen."""
    try:
        r = subprocess.run(
            ["sudo", "-n", "-v"],
            capture_output=True, check=False, timeout=5,
        )
        return r.returncode == 0
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return False


def cache(password: str) -> bool:
    """Validiert Passwort + cached sudo-Credentials.

    Wir nutzen `sudo -S -v -p ''` (lies pw von stdin, nur cache update,
    leerer prompt). Returns True wenn akzeptiert."""
    try:
        r = subprocess.run(
            ["sudo", "-S", "-v", "-p", ""],
            input=password + "\n",
            capture_output=True, text=True, check=False, timeout=10,
        )
        return r.returncode == 0
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return False


def keep_alive() -> None:
    """Verlängert den sudo cache nochmal, falls noch gültig.

    Praktisch in laufenden Updates die mehrere Minuten dauern können."""
    try:
        subprocess.run(
            ["sudo", "-n", "-v"],
            capture_output=True, check=False, timeout=5,
        )
    except (FileNotFoundError, subprocess.TimeoutExpired):
        pass
