"""Shared systemd service status utilities (DRY consolidation).

Provides a single function to check if a systemd user service is active,
replacing identical subprocess patterns in sidecar, kintsugi, and heartbeat.
"""

from __future__ import annotations

import subprocess


def is_systemd_service_active(unit_name: str, *, user_mode: bool = True) -> bool:
    """Check if a systemd service unit is currently active.

    Parameters
    ----------
    unit_name
        Full systemd unit name (e.g. ``"opendeviationbar-kintsugi"``).
    user_mode
        If ``True`` (default), use ``--user`` flag for user-level services.
    """
    cmd = ["systemctl"]
    if user_mode:
        cmd.append("--user")
    cmd.extend(["is-active", unit_name])

    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=5,
            check=False,
        )
        return result.stdout.strip() == "active"
    except (FileNotFoundError, OSError, subprocess.TimeoutExpired):
        return False
