"""
tasks.py
All tasks related to federation:
- Updating node info (number of users, posts etc)
"""

from collections.abc import Sequence
from typing import Any, Callable, override
import uuid

from temporalio.worker import Worker
from temporalio.worker.workflow_sandbox import SandboxRestrictions, SandboxedWorkflowRunner

from phederation.federation.tasks import BackgroundTask


class WorkerTask(BackgroundTask):
    def __init__(self, workflows: Sequence[type], activities: Sequence[Callable[..., Any]]):
        super().__init__()
        self.workflows: Sequence[type] = workflows
        self.activities: Sequence[Callable[..., Any]] = activities

    @override
    async def on_startup(self):
        if not self.server:
            raise ValueError("Worker task not properly initialized")
        if not self.server.settings.worker.enabled or not self.server.worker_client:
            raise ValueError("Worker disabled")
        
        if not self.server.settings.worker.start_own_worker:
            self.logger.info("Starting an instance-owned worker is disabled, there must be workers started in separate processes.")
            return
        
        self.logger.debug("Worker starting...")
        worker = Worker(
            self.server.worker_client,
            identity=f"phederation-worker-{str(uuid.uuid4())[:8]}",
            workflow_runner=SandboxedWorkflowRunner(
                restrictions=SandboxRestrictions.default.with_passthrough_modules("pydantic", "annotated_types", "pydantic_core")
            ),
            task_queue=self.server.settings.worker.tasks_queue_name,
            workflows=self.workflows,
            activities=self.activities,
        )
        self.logger.debug("Worker started.")
        await worker.run()
        self.logger.debug("Worker shutdown.")
