"""Rate limiter for SEC API requests."""

from collections import deque
from time import sleep, time


class rate_limiter:
    """
    Implements a rate limiter for restricting SEC website request rates.

    Arguments:
        interval: limit interval in seconds
        limit: maximum requests per interval

    Usage:
        limiter = rate_limiter(limit_interval, max_requests_per_interval)
        if limiter.allow():
            # Submit file request
    """

    def __init__(self, interval: float, limit: int) -> None:
        self.interval = interval
        self.limit = limit
        self.req_times: deque[float] = deque([time() - interval], maxlen=limit)

    def allow(self, verbose: bool = False) -> bool:
        """
        Returns True if within the rate limit, or blocks until within limit.

        Args:
            verbose: if True, print waiting message when rate limited

        Returns:
            True once rate limit allows the request
        """
        delay = self.interval - (time() - self.req_times[0])
        if delay > 0:
            if verbose:
                print("waiting... ", delay)
            sleep(delay)

        self.req_times.append(time())
        return True
