"""asyncio compatibility shim for Python 3.8.

`asyncio.to_thread` only exists from Python 3.9. The Jetson runs 3.8, so we
backfill it via run_in_executor on the default thread pool.

Usage:
    from Project.Sanad.core.asyncio_compat import to_thread
    result = await to_thread(blocking_fn, arg1, arg2, kw=val)
"""

from __future__ import annotations

import asyncio
import functools
import sys
from typing import Any, Callable, TypeVar

_T = TypeVar("_T")

if sys.version_info >= (3, 9):
    # Native implementation
    to_thread = asyncio.to_thread  # type: ignore[attr-defined]
else:
    async def to_thread(func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> _T:
        """Backport of asyncio.to_thread for Python 3.8."""
        loop = asyncio.get_event_loop()
        ctx = functools.partial(func, *args, **kwargs)
        return await loop.run_in_executor(None, ctx)

# Also patch the asyncio module so existing `asyncio.to_thread` calls work
# without rewriting every consumer file. Done lazily — only if missing.
if not hasattr(asyncio, "to_thread"):
    asyncio.to_thread = to_thread  # type: ignore[attr-defined]
