from __future__ import annotations

from app.core.command_runner import CommandRunner


class ServiceManager:
    def __init__(self, command_runner: CommandRunner) -> None:
        self.command_runner = command_runner

    def enable_service(self, service_name: str) -> None:
        self.command_runner.run(["systemctl", "enable", service_name])

    def disable_service(self, service_name: str) -> None:
        self.command_runner.run(["systemctl", "disable", service_name])

    def start_service(self, service_name: str) -> None:
        self.command_runner.run(["systemctl", "start", service_name])

    def stop_service(self, service_name: str) -> None:
        self.command_runner.run(["systemctl", "stop", service_name])

    def restart_service(self, service_name: str) -> None:
        self.command_runner.run(["systemctl", "restart", service_name])

    def get_service_status(self, service_name: str) -> dict[str, object]:
        active = self._query(["systemctl", "is-active", service_name]) == "active"
        enabled = self._query(["systemctl", "is-enabled", service_name]) == "enabled"
        return {
            "serviceName": service_name,
            "active": active,
            "enabled": enabled,
            "status": "running" if active else "stopped",
        }

    def _query(self, command: list[str]) -> str:
        try:
            return self.command_runner.run(command).stdout.strip()
        except Exception:
            return "unknown"

