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

from csirtmu.core.temporal.config import TemporalConfig, create_temporal_client
from temporalio import activity
from temporalio.api.enums.v1.workflow_pb2 import WorkflowExecutionStatus

from csirtmu.beta_temporal.workflows.logging import LoggedActivities


class TemporalCommonActions(LoggedActivities):
    def __init__(self, config: TemporalConfig) -> None:
        self.config = config

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

    @activity.defn
    async def cancel_workflow(self, workflow_id: str, task_queue: str) -> None:
        self.log_activity()
        client = await create_temporal_client(self.config, task_queue)
        handle = client.get_workflow_handle(workflow_id)  # type: ignore
        await handle.cancel()
        # wait for cancellation
        desc = await handle.describe()
        while desc.status == WorkflowExecutionStatus.WORKFLOW_EXECUTION_STATUS_RUNNING:
            await asyncio.sleep(0.5)
            desc = await handle.describe()
