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

from temporalio import activity, workflow

from csirtmu.beta_temporal.commons.actions.temporal_common_actions import TemporalCommonActions
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 LoggedActivities, LoggedWorkflow


class LinkWithTicketOnLinkWithHeaderActivities(LoggedActivities):
    def __init__(self, rt_client: RTClient) -> None:
        self.rt_client = rt_client

    def get_activities(self) -> Sequence[Callable[..., Any]]:
        return [self.has_link_with_header, self.link_with_ticket]

    @activity.defn
    async def has_link_with_header(self, transaction: structs.TransactionStruct) -> bool:
        self.log_activity()
        ticket_data = self.rt_client.get_ticket_data(transaction)
        return ticket_data is not None and ticket_data.headers.get("X-RT-Link-With") is not None

    @activity.defn
    async def link_with_ticket(self, transaction: structs.TransactionStruct) -> None:
        self.log_activity()
        if transaction.ticket_obj is None or (ticket_data := self.rt_client.get_ticket_data(transaction)) is None:
            return
        self.rt_client.edit_link(transaction.ticket_obj.id, "RefersTo", ticket_data.headers.get("X-RT-Link-With", ""))


class LinkWithTicketOnLinkWithHeader(
    LoggedWorkflow, workflow_name=WorkflowReference.LINK_WITH_TICKET_ON_LINK_WITH_HEADER
):
    @classmethod
    def get_activities(cls) -> Sequence[Callable[..., Awaitable[Any]]]:
        config = AppConfig.get()
        local_activities = LinkWithTicketOnLinkWithHeaderActivities(RTClient(config.rt))
        temporal_activities = TemporalCommonActions(config.temporal)
        return [*local_activities.get_activities(), *temporal_activities.get_activities()]

    @workflow.run
    async def run(self, transaction: structs.TransactionStruct) -> None:
        self.log_workflow()
        config = AppConfig.get()
        if await workflow.execute_activity(
            LinkWithTicketOnLinkWithHeaderActivities.has_link_with_header,
            args=(transaction,),
            retry_policy=config.temporal.retry_policy,
            start_to_close_timeout=config.temporal.activity_timeout,
        ):
            await workflow.execute_activity(
                LinkWithTicketOnLinkWithHeaderActivities.link_with_ticket,
                args=(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,
            )
