"""Helpers for coordinating asyncio state across threads and event loops."""

from __future__ import annotations

import asyncio
import threading


class LoopBoundAsyncLock:
    """Create one ``asyncio.Lock`` per running loop without cross-thread races."""

    def __init__(self) -> None:
        self._guard = threading.Lock()
        self._lock: asyncio.Lock | None = None
        self._loop: asyncio.AbstractEventLoop | None = None

    def get(self) -> asyncio.Lock:
        """Return the lock for the current loop, creating it safely if needed."""
        loop = asyncio.get_running_loop()
        with self._guard:
            if self._lock is None or self._loop is not loop:
                self._lock = asyncio.Lock()
                self._loop = loop
            return self._lock


__all__ = ["LoopBoundAsyncLock"]
