import time
import structlog
from .client import Plugin

log = structlog.get_logger("careful")


class ThrottlePlugin(Plugin):
    def __init__(self, requests_per_minute: float = 0):
        if requests_per_minute <= 0:
            raise ValueError("requests per minute must be a positive number")
        self._last_request = 0.0
        self._requests_per_minute = requests_per_minute
        self._request_frequency = 60.0 / requests_per_minute

    def wrap(self, next_handler, client):
        def throttle_handler(method, url, **kwargs):
            now = time.time()
            diff = self._request_frequency - (now - self._last_request)
            if diff > 0:
                log.debug("throttled", sleep=diff)
                time.sleep(diff)
                self._last_request = time.time()
            else:
                self._last_request = now
            return next_handler(method, url, **kwargs)

        return throttle_handler
