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

from temporalio import activity, workflow

from csirtmu.beta_temporal.commons.actions import RTCommonActions
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.external_services.rt.utils import get_auto_reply_map, search_for_keyword_in_header
from csirtmu.beta_temporal.workflows.logging import LoggedActivities, LoggedWorkflow


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

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

    @activity.defn
    async def is_autoresponse(self, transaction: structs.TransactionStruct) -> bool:
        self.log_activity()
        if (data := self.rt_client.get_ticket_data(transaction)) is None:
            return False
        auto_reply_map = get_auto_reply_map()
        return any(
            search_for_keyword_in_header(data.headers, "From", key)
            and (
                any(keyword in data.body for keyword in auto_reply_map[key]["Content"])
                or any(
                    search_for_keyword_in_header(data.headers, "Subject", keyword)
                    for keyword in auto_reply_map[key]["Subject"]
                )
            )
            for key in auto_reply_map
        )


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

    @workflow.run
    async def run(self, transaction: structs.TransactionStruct) -> None:
        self.log_workflow()
        if transaction.ticket_obj is None:
            return
        config = AppConfig.get()
        if await workflow.execute_activity(
            HandleGenericAutorepliesActivities.is_autoresponse,
            args=(transaction,),
            retry_policy=config.temporal.retry_policy,
            start_to_close_timeout=config.temporal.activity_timeout,
        ):
            await workflow.execute_activity(
                RTCommonActions.set_custom_field,
                args=("Category", "Generic autoreply", transaction),
                retry_policy=config.temporal.retry_policy,
                start_to_close_timeout=config.temporal.activity_timeout,
            )
            await workflow.execute_activity(
                RTCommonActions.close_ticket,
                args=(transaction.ticket_obj.id,),
                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,
            )
