from dataclasses import dataclass

from gateway_core.domain.Reboot import RebootDto, RebootEntity, RebootType
from gateway_node_agent.application.ports.rebootExecutorPort import RebootExecutorPort
from gateway_platform.systemd.SystemdManagerClient import SystemdManagerClient


@dataclass(frozen=True, slots=True)
class SystemdUnitRestartAdapter(RebootExecutorPort):
    """
    Infrastructure adapter for restarting a systemd unit using DBus.

    Implemented as an immutable, slot-based dataclass to keep the adapter
    stateless, memory-efficient, and safe against accidental runtime mutation.
    The adapter is instantiated once during application composition and reused
    for the entire application lifetime.

    :param systemd: systemd DBus client used to restart the unit.
    :param unitName: Name of the systemd unit to restart.
    :param allowedEntity: Reboot entity this adapter is allowed to handle.
    :param allowedType: Reboot type this adapter is allowed to handle.
    :param isArmed: Safety flag to enable or disable unit restart execution.
    """

    systemd: SystemdManagerClient
    unitName: str
    allowedEntity: RebootEntity
    allowedType: RebootType
    isArmed: bool = False

    def canHandle(self, dto: RebootDto) -> bool:
        return dto.entity == self.allowedEntity and dto.type == self.allowedType

    async def execute(self, dto: RebootDto) -> None:
        if not self.isArmed:
            return

        await self.systemd.restartUnit(self.unitName)
