import time
from aiva.monitoring import metrics

class ThrottlingStrategy:
    def __init__(self):
        pass

    def should_throttle(self, email):
        raise NotImplementedError

    def before_send(self, email):
        # Update metrics before processing an email.
        metrics.EMAIL_QUEUE_SIZE.inc()

    def after_send(self, email, success=True):
        # Update metrics after processing an email.
        metrics.EMAIL_QUEUE_SIZE.dec()
        if success:
            metrics.EMAIL_SENT_SUCCESS_COUNT.inc()
        else:
            metrics.EMAIL_DROPPED_COUNT.inc()

class ExampleThrottlingStrategy(ThrottlingStrategy):
    def __init__(self, rate_limit=10, time_window=60):
        super().__init__()
        self.rate_limit = rate_limit
        self.time_window = time_window
        self.email_timestamps = []

    def should_throttle(self, email):
        now = time.time()
        self.email_timestamps = [ts for ts in self.email_timestamps if ts > now - self.time_window]
        if len(self.email_timestamps) >= self.rate_limit:
            return True
        else:
            return False

    def before_send(self, email):
        super().before_send(email)
        # Simulate processing time for demonstration purposes.
        start_time = time.time()
        time.sleep(0.1) # Simulate processing time
        end_time = time.time()
        processing_time = end_time - start_time
        metrics.EMAIL_PROCESSING_TIME.observe(processing_time)

        # Add timestamp for rate limiting.
        self.email_timestamps.append(time.time())


# Example usage in a hypothetical email sending function

def send_email(email, throttling_strategy):
    throttling_strategy.before_send(email)
    try:
        if throttling_strategy.should_throttle(email):
            print(f"Email throttled for: {email}")
            throttling_strategy.after_send(email, success=False)
            return False # Indicate failure

        # Simulate sending the email
        print(f"Sending email: {email}")
        # ... actual email sending logic ...
        time.sleep(0.2) # Simulate sending time.
        throttling_strategy.after_send(email, success=True)
        return True # Indicate success

    except Exception as e:
        print(f"Error sending email: {e}")
        throttling_strategy.after_send(email, success=False)
        return False


if __name__ == '__main__':
    from aiva.monitoring import metrics
    metrics.initialize_metrics()

    # Example Usage
    strategy = ExampleThrottlingStrategy(rate_limit=2, time_window=5)
    emails_to_send = ["email1@example.com", "email2@example.com", "email3@example.com", "email4@example.com"]

    for email in emails_to_send:
        send_email(email, strategy)
        time.sleep(1)

    # Let the Prometheus server run for a while to collect metrics
    print("Letting Prometheus collect metrics... check localhost:8000")
    time.sleep(10)
    print("Done.")
