from collections.abc import Awaitable, Callable, Sequence
from typing import Any

from temporalio import workflow

from csirtmu.beta_temporal.commons.actions import MattermostActions
from csirtmu.beta_temporal.commons.actions.temporal_common_actions import TemporalCommonActions
from csirtmu.beta_temporal.commons.conditions import CommonConditions
from csirtmu.beta_temporal.config import AppConfig
from csirtmu.beta_temporal.constants import WorkflowReference
from csirtmu.beta_temporal.external_services.mattermost.client import MattermostClient
from csirtmu.beta_temporal.external_services.rt import structs
from csirtmu.beta_temporal.external_services.rt.client import RTClient
from csirtmu.beta_temporal.workflows.logging import LoggedWorkflow


class MattermostNotificationOnCertificateTicket(
    LoggedWorkflow, workflow_name=WorkflowReference.MATTERMOST_NOTIFICATION_ON_CERTIFICATE_TICKET
):
    @classmethod
    def get_activities(cls) -> Sequence[Callable[..., Awaitable[Any]]]:
        config = AppConfig.get()
        common = CommonConditions(RTClient(config.rt))
        mattermost = MattermostActions(config.rt.base_url, MattermostClient(config.mattermost))
        temporal = TemporalCommonActions(config.temporal)
        return [*common.get_activities(), *mattermost.get_activities(), *temporal.get_activities()]

    @workflow.run
    async def run(self, transaction: structs.TransactionStruct, params: dict[str, str]) -> None:
        self.log_workflow()
        config = AppConfig.get()
        if not (channel := params.get("mm_channel")):
            raise ValueError("No channel given!")
        if await workflow.execute_activity(
            CommonConditions.is_certificate_notification,
            args=(transaction,),
            retry_policy=config.temporal.retry_policy,
            start_to_close_timeout=config.temporal.activity_timeout,
        ):
            await workflow.execute_activity(
                MattermostActions.notify_mattermost_on_certificate_ticket,
                args=(transaction, channel),
                retry_policy=config.temporal.retry_policy,
                start_to_close_timeout=config.temporal.activity_timeout,
            )
        elif config.temporal.allow_internal_cancels:
            await workflow.execute_activity(
                TemporalCommonActions.cancel_workflow,
                args=(workflow.info().workflow_id, workflow.info().task_queue),
                retry_policy=config.temporal.retry_policy,
                start_to_close_timeout=config.temporal.activity_timeout,
            )
