import logging

from gateway_core.application.orchestrators.SoftwareUpgradeOrchestrator import SoftwareUpgradeOrchestrator
from gateway_core.application.ports.NotificationPort import NotificationPort
from gateway_core.domain.SoftwareUpgrade import SoftwareUpgradeDto, SoftwareUpgradeStatus

logger = logging.getLogger(__name__)


class SoftwareUpgradeUseCase:
    def __init__(
        self,
        orchestrator: SoftwareUpgradeOrchestrator,
        notifier: NotificationPort,
    ) -> None:
        self._orchestrator = orchestrator
        self._notifier = notifier

    async def execute(self, dto: SoftwareUpgradeDto) -> None:
        logger.info("Received software upgrade request: %s", dto)
        await self._notifier.notifySoftwareUpgradeStatus(dto=dto, status=SoftwareUpgradeStatus.REQUESTED)

        try:
            await self._orchestrator.upgrade(dto=dto)
            await self._notifier.notifySoftwareUpgradeStatus(dto=dto, status=SoftwareUpgradeStatus.RUNNING)
        except Exception:
            logger.exception("Software upgrade failed")
            await self._notifier.notifySoftwareUpgradeStatus(dto=dto, status=SoftwareUpgradeStatus.FAILED)
            raise
