from __future__ import annotations

import asyncio
from dataclasses import dataclass
from typing import Any, Callable, cast


@dataclass(frozen=True)
class SyncToAsyncGatewayAdapter:
    """Adapt a sync gateway object to an async protocol.

    Attribute access is delegated to the underlying sync gateway. If the attribute
    is callable, we return an `async def` wrapper that runs it in a worker thread
    via `asyncio.to_thread`.
    """

    sync_gateway: Any

    def __getattr__(self, name: str) -> Any:  # noqa: ANN401
        target = getattr(self.sync_gateway, name)
        if not callable(target):
            return target

        fn = cast(Callable[..., Any], target)

        async def _wrapped(*args: Any, **kwargs: Any) -> Any:
            return await asyncio.to_thread(fn, *args, **kwargs)

        return _wrapped

    async def aclose(self) -> None:
        close = getattr(self.sync_gateway, "close", None)
        if callable(close):
            await asyncio.to_thread(close)

