import logging
from aiva.notifications.slack import SlackNotifier  # Assuming slack.py is in aiva.notifications package
import datetime

logger = logging.getLogger(__name__)

class AlertHandler:
    def __init__(self, config):
        self.config = config
        self.notification_enabled = config.get('notification_enabled', False)
        self.notification_channel = config.get('notification_channel', None)
        self.notifier = None

        if self.notification_enabled and self.notification_channel:
            self.notifier = SlackNotifier(self.notification_channel)
            logger.info("Alert handler initialized with Slack notifications.")
        elif self.notification_enabled:
            logger.warning("Notification enabled but no channel specified. Notifications will be disabled.")
            self.notification_enabled = False

    def handle_alert(self, metric_name, current_value, threshold_value):
        """Handles a triggered alert by sending a notification.

        Args:
            metric_name (str): The name of the metric that triggered the alert.
            current_value (float): The current value of the metric.
            threshold_value (float): The threshold value that was exceeded.
        """
        if not self.notification_enabled or self.notifier is None:
            logger.debug("Notifications are disabled or not configured.")
            return

        timestamp = datetime.datetime.now().isoformat()
        message = f"Alert triggered!\nMetric: {metric_name}\nCurrent Value: {current_value}\nThreshold: {threshold_value}\nTimestamp: {timestamp}"

        if self.notifier.send_message(message):
            logger.info("Alert notification sent successfully.")
        else:
            logger.error("Failed to send alert notification.")


if __name__ == '__main__':
    # Example usage (for testing)
    logging.basicConfig(level=logging.DEBUG)
    config = {
        'notification_enabled': True,
        'notification_channel': 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX' # Replace with your actual Slack webhook URL
    }
    alert_handler = AlertHandler(config)
    alert_handler.handle_alert("email_throttle_rate", 0.95, 0.9)
