import datetime
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.workflows.logging import LoggedActivities, LoggedWorkflow


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

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

    @activity.defn
    async def set_starts_on_create(self, transaction: structs.TransactionStruct) -> None:
        self.log_activity()
        if transaction.ticket_obj is None:
            return
        now = datetime.datetime.now(tz=datetime.UTC)
        weekday = now.weekday()
        if weekday == 5 or weekday == 6:
            now += datetime.timedelta(days=7 - weekday)
            now = now.replace(hour=0, minute=0, second=0)
        self.rt_client.edit_ticket(transaction.ticket_obj.id, Starts=now.strftime("%Y-%m-%d %H:%M:%S"))


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

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