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

from temporalio import activity, workflow

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
from csirtmu.beta_temporal.workflows.logging import LoggedActivities, LoggedWorkflow


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

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

    @activity.defn
    async def set_report_uuid(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
        if report_uuid := get_header(ticket_data.headers, "X-RT-Report-UUID"):
            self.rt_client.edit_ticket(transaction.ticket_obj.id, CustomFields={"uuid": report_uuid[0]})


class SetReportUUID(LoggedWorkflow, workflow_name=WorkflowReference.SET_REPORT_UUID):
    @classmethod
    def get_activities(cls) -> Sequence[Callable[..., Awaitable[Any]]]:
        config = AppConfig.get()
        return SetReportUUIDActivities(RTClient(config.rt)).get_activities()

    @workflow.run
    async def run(self, transaction: structs.TransactionStruct) -> None:
        self.log_workflow()
        config = AppConfig.get()
        await workflow.execute_activity(
            SetReportUUIDActivities.set_report_uuid,
            args=(transaction,),
            retry_policy=config.temporal.retry_policy,
            start_to_close_timeout=config.temporal.activity_timeout,
        )
