"""Firewall — einfacher An/Aus-Status. UI-frei. Bevorzugt ufw, sonst firewalld.

Status ist ohne root lesbar (systemctl is-active); Umschalten läuft privilegiert
über den Helper.
"""
from __future__ import annotations

import shutil
import subprocess


def backend() -> str | None:
    if shutil.which("ufw"):
        return "ufw"
    if shutil.which("firewall-cmd"):
        return "firewalld"
    return None


def installed() -> bool:
    return backend() is not None


def _service() -> str:
    return "firewalld" if backend() == "firewalld" else "ufw"


def enabled() -> bool:
    try:
        r = subprocess.run(["systemctl", "is-active", _service()],
                          capture_output=True, text=True, check=False, timeout=5)
        return r.stdout.strip() == "active"
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return False


def set_enabled_argv(on: bool) -> list[str]:
    if backend() == "ufw":
        return ["ufw", "enable"] if on else ["ufw", "disable"]
    action = "enable" if on else "disable"
    return ["systemctl", action, "--now", "firewalld"]


def install_argv() -> list[str]:
    return ["pacman", "-S", "--needed", "--noconfirm", "ufw"]
