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.mattermost.client import MattermostClient
from csirtmu.beta_temporal.external_services.netbox.client import NetboxClient
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
from csirtmu.beta_temporal.utils import contains_friendly_address, parse_ip_addresses
from csirtmu.beta_temporal.workflows.logging import LoggedActivities, LoggedWorkflow


class MattermostNotificationOnAutomaticTicketFromUniActivities(LoggedActivities):
    def __init__(
        self, rt_client: RTClient, netbox_client: NetboxClient, mm_client: MattermostClient, rt_host: str
    ) -> None:
        self.rt_client = rt_client
        self.netbox_client = netbox_client
        self.mm_client = mm_client
        self.rt_host = rt_host

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

    @activity.defn
    async def is_automatic_ticket_from_uni(self, transaction: structs.TransactionStruct) -> bool:
        self.log_activity()
        if (ticket_data := self.rt_client.get_ticket_data(transaction)) is None:
            return False
        senders = get_header(ticket_data.headers, "From")
        ips = get_header(ticket_data.headers, "X-RT-Incident-IP")
        return (
            any(
                [
                    (
                        ip != ""
                        and (info := await self.netbox_client.get_subnet_info_on_ip(ip)) is not None
                        and (info.prefixes or info.ip_addresses)
                    )
                    for ip in ips
                ]
            )
            or contains_friendly_address(parse_ip_addresses(ips))
        ) and any(re.search(r"ToolGateway", sender, re.IGNORECASE) for sender in senders)

    @activity.defn
    async def notify_mattermost_on_automatic_ticket(self, transaction: structs.TransactionStruct, channel: str) -> None:
        self.log_activity()
        if transaction.ticket_obj is None or (ticket_data := self.rt_client.get_ticket_data(transaction)) is None:
            return
        subject = (
            ticket_data.attachments[0].subject if (len(ticket_data.attachments) > 0) else transaction.ticket_obj.subject
        )
        message = f"New ticket in Automatic: {subject}, link: {self.rt_host}Ticket/Display.html?id={transaction.ticket_obj.id}"
        self.mm_client.send_message(message, channel=channel, username="rt_bot", icon_emoji="sauron")


class MattermostNotificationOnAutomaticTicketFromUni(
    LoggedWorkflow, workflow_name=WorkflowReference.MATTERMOST_NOTIFICATION_ON_AUTOMATIC_TICKET_FROM_UNI
):
    @classmethod
    def get_activities(cls) -> Sequence[Callable[..., Awaitable[Any]]]:
        config = AppConfig.get()
        condition = MattermostNotificationOnAutomaticTicketFromUniActivities(
            RTClient(config.rt), NetboxClient(config.netbox), MattermostClient(config.mattermost), config.rt.base_url
        )
        temporal = TemporalCommonActions(config.temporal)
        return [*condition.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(
            MattermostNotificationOnAutomaticTicketFromUniActivities.is_automatic_ticket_from_uni,
            args=(transaction,),
            retry_policy=config.temporal.retry_policy,
            start_to_close_timeout=config.temporal.activity_timeout,
        ):
            await workflow.execute_activity(
                MattermostNotificationOnAutomaticTicketFromUniActivities.notify_mattermost_on_automatic_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,
            )
