import re
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.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 CloseAutomaticTicketsFromOutsideActivities(LoggedActivities):
    def __init__(self, rt_client: RTClient, netbox_client: NetboxClient) -> None:
        self.rt_client = rt_client
        self.netbox_client = netbox_client

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

    @activity.defn
    async def is_automatic_create_from_outside(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")
        actors = get_header(ticket_data.headers, "X-RT-Incident-Actors")
        if (
            (
                any(re.search(r"ToolGateway", sender, re.IGNORECASE) for sender in senders)
                and any(re.search(r"^147\.251\.", ip) for ip in ips)
            )
            or any(re.search(r"147\.251\.\d{1,3}\.\d{1,3}", actor) for actor in actors)
            or any(re.search(r"UCO=", actor) for actor in actors)
            or "1" in get_header(ticket_data.headers, "X-RT-Manual-Handling")
        ):
            return False
        for ip in ips:
            if (
                ip != ""
                and (info := await self.netbox_client.get_subnet_info_on_ip(ip)) is not None
                and (info.prefixes or info.ip_addresses)
            ):
                return False
        if contains_friendly_address(parse_ip_addresses(ips)):
            return False
        return transaction.ticket_obj is not None and (
            (
                transaction.ticket_obj.status.lower() == "new"
                and any(re.search(r"ToolGateway", sender, re.IGNORECASE) for sender in senders)
            )
            or (
                transaction.ticket_obj.status.lower() == "act"
                and any(re.search(r"ToolGateway", sender, re.IGNORECASE) for sender in senders)
            )
        )


class CloseAutomaticTicketsFromOutside(
    LoggedWorkflow, workflow_name=WorkflowReference.CLOSE_AUTOMATIC_TICKETS_FROM_OUTSIDE
):
    @classmethod
    def get_activities(cls) -> Sequence[Callable[..., Awaitable[Any]]]:
        config = AppConfig.get()
        rt_client = RTClient(config.rt)
        temporal_activities = TemporalCommonActions(config.temporal)
        rt_activities = RTCommonActions(rt_client)
        activities = CloseAutomaticTicketsFromOutsideActivities(rt_client, NetboxClient(config.netbox))
        return [*temporal_activities.get_activities(), *rt_activities.get_activities(), *activities.get_activities()]

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