import asyncio
import time

class RateLimiter:
    """
    Centralized Request Queue that enforces a physical delay between API calls.
    Default delay is 250ms (4 requests per second).
    """
    def __init__(self):
        self._lock = asyncio.Lock()
        self._last_call_time = 0
        self._delay = 0.25  # seconds (250ms)

    async def wait(self):
        """
        Acquire lock and sleep if necessary to respect the rate limit.
        """
        async with self._lock:
            now = time.monotonic()
            elapsed = now - self._last_call_time
            
            if elapsed < self._delay:
                sleep_time = self._delay - elapsed
                await asyncio.sleep(sleep_time)
            
            self._last_call_time = time.monotonic()

    def set_delay(self, ms: int):
        """
        Update the delay interval dynamically from DB settings.
        """
        self._delay = ms / 1000.0

# Singleton instance
global_rate_limiter = RateLimiter()
