"""Async transport helpers for the Sandai operator client."""

from __future__ import annotations

import asyncio
from typing import Any, Dict, Optional

from .config import ClientConfig
from .transport import CeleryTransport
from .debug_output import PrintLogger

logger = PrintLogger(__name__, enabled=False)


class AsyncTransportAdapter:
    """Async wrapper over the shared synchronous Celery transport."""

    def __init__(self, config: ClientConfig, logger_: Optional[Any] = None):
        self.config = config
        self.logger = logger_ or PrintLogger(__name__, enabled=config.debug)
        self.celery = CeleryTransport(config, logger=self.logger)
        self.app = self.celery.app
        self._closed = False
        if self.config.debug:
            self.logger.debug(
                "async_transport_initialized operator=%s version=%s",
                self.config.operator_name,
                self.config.operator_version,
            )

    async def aclose(self) -> None:
        if self._closed:
            return
        self._closed = True
        if self.config.debug:
            self.logger.debug(
                "async_transport_close operator=%s version=%s",
                self.config.operator_name,
                self.config.operator_version,
            )
        await asyncio.to_thread(self.celery.close)

    async def send_task(self, task_name: str, *, kwargs: Dict[str, Any], queue: str) -> Any:
        if self.config.debug:
            self.logger.debug("async_transport_send queue=%s", queue)
        return await asyncio.to_thread(
            self.celery.send_task,
            task_name,
            kwargs=kwargs,
            queue=queue,
        )

    async def get_result(self, async_result: Any, *, timeout: int) -> Any:
        if self.config.debug:
            self.logger.debug("async_transport_get_result task_id=%s timeout=%s", getattr(async_result, "id", None), timeout)
        return await asyncio.to_thread(self.celery.get_result, async_result, timeout=timeout)

    async def forget(self, async_result: Any) -> None:
        if self.config.debug:
            self.logger.debug("async_transport_forget task_id=%s", getattr(async_result, "id", None))
        await asyncio.to_thread(self.celery.forget, async_result)

    async def result_exists(self, async_result: Any) -> bool:
        if self.config.debug:
            self.logger.debug("async_transport_result_exists task_id=%s", getattr(async_result, "id", None))
        return await asyncio.to_thread(self.celery.result_exists, async_result)

    async def get_state(self, async_result: Any) -> str:
        if self.config.debug:
            self.logger.debug("async_transport_get_state task_id=%s", getattr(async_result, "id", None))
        return await asyncio.to_thread(self.celery.get_state, async_result)

    async def collect_ready_results(self, async_results: list[Any], *, wait_for_slot: bool = True) -> dict[str, Any]:
        if self.config.debug:
            self.logger.debug(
                "async_transport_collect_ready_results count=%s wait_for_slot=%s",
                len(async_results),
                wait_for_slot,
            )
        return await asyncio.to_thread(
            self.celery.collect_ready_results,
            async_results,
            wait_for_slot=wait_for_slot,
        )
