import time
import logging

logger = logging.getLogger(__name__)

class RateLimiter:
    def __init__(self):
        self.limits = {}

    def configure_limit(self, threshold_name, limit_seconds):
        """Configures a rate limit for a specific threshold.

        Args:
            threshold_name (str): The name of the threshold (e.g., 'high_cpu', 'low_memory').
            limit_seconds (int): The time in seconds to wait between actions for this threshold.
        """
        self.limits[threshold_name] = {
            'limit': limit_seconds,
            'last_triggered': None
        }

    def check_and_update(self, threshold_name):
        """Checks if the rate limit for a threshold has been exceeded and updates the last triggered time.

        Args:
            threshold_name (str): The name of the threshold.

        Returns:
            bool: True if the action can proceed, False if it should be delayed.
        """
        if threshold_name not in self.limits:
            return True  # No limit configured, so allow the action

        limit_data = self.limits[threshold_name]
        limit = limit_data['limit']
        last_triggered = limit_data['last_triggered']

        if last_triggered is None:
            self.limits[threshold_name]['last_triggered'] = time.time()
            return True

        elapsed_time = time.time() - last_triggered

        if elapsed_time >= limit:
            self.limits[threshold_name]['last_triggered'] = time.time()
            return True
        else:
            remaining_time = limit - elapsed_time
            logger.warning(f"Rate limit for threshold '{threshold_name}' exceeded. Delaying action for {remaining_time:.2f} seconds.")
            return False

    def reset_limit(self, threshold_name):
        """Resets the rate limit for a specific threshold.

        Args:
            threshold_name (str): The name of the threshold.
        """
        if threshold_name in self.limits:
            self.limits[threshold_name]['last_triggered'] = None
