# Copyright (c) 2025 CoReason, Inc.
#
# This software is proprietary and dual-licensed.
# Licensed under the Prosperity Public License 3.0 (the "License").
# A copy of the license is available at https://prosperitylicense.com/versions/3.0.0
# For details, see the LICENSE file.
# Commercial use beyond a 30-day trial requires a separate license.
#
# Source Code: https://github.com/CoReason-AI/coreason_navigator

import asyncio
import time


class RateLimiter:
    """
    Enforces a minimum time interval between actions.
    Uses a 'Start-to-Start' strategy (delay ensures gap between start times).

    Attributes:
        rate_limit: The minimum time interval in seconds.
    """

    def __init__(self, rate_limit: float = 2.0):
        """
        Initializes the RateLimiter.

        Args:
            rate_limit: Minimum seconds between actions. Defaults to 2.0.
        """
        self.rate_limit = rate_limit
        self._last_action_timestamp: float = 0.0
        self._lock = asyncio.Lock()

    async def wait(self) -> None:
        """
        Waits if necessary to respect the rate limit.

        Calculates the time elapsed since the last action and sleeps for the remainder
        of the rate limit interval if needed.
        """
        async with self._lock:
            now = time.monotonic()
            elapsed = now - self._last_action_timestamp
            if elapsed < self.rate_limit:
                delay = self.rate_limit - elapsed
                await asyncio.sleep(delay)
                # Re-read time after sleep to be precise
                now = time.monotonic()

            self._last_action_timestamp = now
