import re
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.external_services.rt.utils import get_header, get_return_mail_map
from csirtmu.beta_temporal.workflows.logging import LoggedActivities, LoggedWorkflow


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

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

    @activity.defn
    async def is_returned_mail(self, transaction: structs.TransactionStruct) -> bool:
        self.log_activity()
        if transaction.ticket_obj is None or (ticket_data := self.rt_client.get_ticket_data(transaction)) is None:
            return False
        senders = get_header(ticket_data.headers, "From")
        return_mail_map = get_return_mail_map()
        for condition in return_mail_map:
            if (
                (
                    condition["Subject"] is None
                    or re.search(re.escape(condition["Subject"]), transaction.ticket_obj.subject) is not None
                )
                and (
                    condition["Sender"] is None
                    or any(
                        re.search(re.escape(condition["Sender"]), sender, re.IGNORECASE) is not None
                        for sender in senders
                    )
                )
                and (
                    condition["Content"] is None
                    or re.search(r"^\s*" + re.escape(condition["Content"]), ticket_data.body) is not None
                )
            ):
                return True
        return False

    @activity.defn
    async def reject_mail(self, transaction: structs.TransactionStruct) -> None:
        self.log_activity()
        if transaction.ticket_obj is None:
            return
        self.rt_client.edit_custom_field(transaction.ticket_obj.id, "Category", "Unable to contact")
        self.rt_client.edit_ticket(transaction.ticket_obj.id, Status="rejected")


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

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