"""
Cleanup workflow for ephemeral worker queues.

This workflow runs periodically (e.g., every 1 minute) to scan and cleanup
ephemeral queues that have exceeded their TTL.
"""

from datetime import timedelta
from temporalio import workflow
from temporalio.common import RetryPolicy

# Import activity
with workflow.unsafe.imports_passed_through():
    from control_plane_api.worker.activities.cleanup_activities import cleanup_ephemeral_queues


@workflow.defn(name="EphemeralQueueCleanupWorkflow")
class EphemeralQueueCleanupWorkflow:
    """
    Workflow that runs cleanup activities for ephemeral worker queues.

    This workflow should be started as a scheduled workflow that runs
    every 1-5 minutes to cleanup expired ephemeral queues.
    """

    @workflow.run
    async def run(self) -> dict:
        """
        Run the cleanup activity.

        Returns:
            Cleanup statistics: {scanned, cleaned, skipped, errors}
        """

        # Execute cleanup activity with retry policy
        stats = await workflow.execute_activity(
            cleanup_ephemeral_queues,
            schedule_to_close_timeout=timedelta(minutes=2),
            retry_policy=RetryPolicy(
                maximum_attempts=3,
                initial_interval=timedelta(seconds=1),
                maximum_interval=timedelta(seconds=10),
                backoff_coefficient=2.0,
            ),
        )

        workflow.logger.info(
            "cleanup_workflow_complete",
            scanned=stats["scanned"],
            cleaned=stats["cleaned"],
            skipped=stats["skipped"],
            errors=stats["errors"],
        )

        return stats
