"""跨线程安全的异步请求间隔限速。

find_agent 以多线程跑时，每个 worker 自建事件循环；不能用 asyncio.Lock 做进程级限速。
"""
from __future__ import annotations

import asyncio
import threading
import time
from collections.abc import Awaitable, Callable


def make_async_interval_limiter(
    min_interval_seconds: float,
) -> Callable[[], Awaitable[None]]:
    """返回 awaitable 限速函数：保证两次调用间隔不少于 min_interval_seconds。"""
    lock = threading.Lock()
    state = {"next_allowed": 0.0}

    async def _wait() -> None:
        with lock:
            now = time.monotonic()
            wait_seconds = state["next_allowed"] - now
            if wait_seconds < 0:
                wait_seconds = 0.0
            state["next_allowed"] = now + wait_seconds + float(min_interval_seconds)
        if wait_seconds > 0:
            await asyncio.sleep(wait_seconds)

    return _wait
