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

from temporalio import workflow

from csirtmu.beta_temporal.commons.actions import RTCommonActions
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.rt import structs
from csirtmu.beta_temporal.external_services.rt.client import RTClient
from csirtmu.beta_temporal.workflows.logging import LoggedWorkflow


class SetTicketPriorityOnCustomFieldChangeParams(TypedDict):
    cf_name: str
    cf_value: Any
    priority: int


class SetTicketPriorityOnCustomFieldChange(
    LoggedWorkflow, workflow_name=WorkflowReference.SET_TICKET_PRIORITY_ON_CUSTOM_FIELD_CHANGE
):
    @classmethod
    def get_activities(cls) -> Sequence[Callable[..., Awaitable[Any]]]:
        config = AppConfig.get()
        rt_client = RTClient(config.rt)
        rt_actions = RTCommonActions(rt_client)
        common_conditions = CommonConditions(rt_client)
        temporal_actions = TemporalCommonActions(config.temporal)
        return [
            *rt_actions.get_activities(),
            *common_conditions.get_activities(),
            *temporal_actions.get_activities(),
        ]

    @workflow.run
    async def run(
        self, transaction: structs.TransactionStruct, params: SetTicketPriorityOnCustomFieldChangeParams
    ) -> None:
        self.log_workflow()
        config = AppConfig.get()
        if await workflow.execute_activity(
            CommonConditions.custom_field_value_set,
            args=(
                params["cf_name"],
                params["cf_value"],
                transaction,
            ),
            retry_policy=config.temporal.retry_policy,
            start_to_close_timeout=config.temporal.activity_timeout,
        ):
            await workflow.execute_activity(
                RTCommonActions.set_ticket_priority,
                args=(params["priority"], transaction),
                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,
            )
