"""Status de serviços do sistema (BIND9, painel) via systemctl."""
from __future__ import annotations

import subprocess

from .config import get_config


def _systemctl(*args: str) -> tuple[int, str]:
    try:
        res = subprocess.run(
            ["systemctl", *args], capture_output=True, text=True, timeout=15
        )
        return res.returncode, (res.stdout or res.stderr).strip()
    except (FileNotFoundError, subprocess.SubprocessError) as exc:
        return 1, str(exc)


def service_status(name: str) -> dict:
    code, out = _systemctl("is-active", name)
    active = out == "active"
    return {
        "name": name,
        "state": out or "desconhecido",
        "active": active,
        "ok": active and code == 0,
    }


def overview() -> list[dict]:
    cfg = get_config()
    return [service_status(cfg.bind_service), service_status(cfg.panel_service)]


def restart_panel() -> tuple[bool, str]:
    cfg = get_config()
    code, out = _systemctl("restart", cfg.panel_service)
    return code == 0, out
