"""
Async utilities for Dask operations.
"""

from typing import Any, Optional
import asyncio

try:
    from dask.distributed import Client
except ImportError:
    Client = object
from .core import safe_compute, safe_persist


async def async_compute(obj: Any, dask_client: Optional[Client] = None) -> Any:
    """Compute Dask object using async client if available."""
    if dask_client and getattr(dask_client, "asynchronous", False):
        return await dask_client.compute(obj)
    # Offload sync compute (which calls .result()) to a thread
    return await asyncio.to_thread(safe_compute, obj, dask_client)


async def async_persist(obj: Any, dask_client: Optional[Client] = None) -> Any:
    """Persist Dask object using async client if available."""
    if dask_client and getattr(dask_client, "asynchronous", False):
        return await dask_client.persist(obj)
    # Offload sync persist (though usually fast, safe_persist might check active_client)
    return await asyncio.to_thread(safe_persist, obj, dask_client=dask_client)
