import logging
import threading
from aiva.alerts.email_sender import EmailSender
from aiva.alerts.slack_sender import SlackSender

logger = logging.getLogger(__name__)

class AlertManager:
    def __init__(self, config):
        self.config = config
        self.email_sender = EmailSender(config.get('email', {}))
        self.slack_sender = SlackSender(config.get('slack', {}))
        self.alert_suppression_rules = config.get('alert_suppression_rules', [])
        self.lock = threading.Lock()

    def send_alert(self, alert_type, message, details=None):
        with self.lock:
            if self._should_suppress_alert(alert_type, details):
                logger.info(f"Alert suppressed: {alert_type} - {message}")
                return

            if self.config.get('email', {}).get('enabled', False):
                try:
                    self.email_sender.send_email(subject=f"AIVA Alert: {alert_type}", body=message, details=details)
                except Exception as e:
                    logger.error(f"Failed to send email alert: {e}")

            if self.config.get('slack', {}).get('enabled', False):
                try:
                    self.slack_sender.send_slack_message(message=f"*AIVA Alert: {alert_type}*\n{message}\nDetails: {details}")
                except Exception as e:
                    logger.error(f"Failed to send Slack alert: {e}")

    def _should_suppress_alert(self, alert_type, details):
        for rule in self.alert_suppression_rules:
            if rule.get('alert_type') == alert_type:
                # Implement more complex suppression logic here based on 'details'
                # For example, check if a specific parameter in 'details' matches a certain value.
                # Right now, it just suppresses based on alert_type.
                return True
        return False

    def configure_alert_thresholds(self, thresholds):
        # Placeholder for configuring alert thresholds.  This functionality would
        # depend on the specific data being monitored and the desired alerting behavior.
        logger.info(f"Alert thresholds configured: {thresholds}")

    def configure_escalation_policies(self, policies):
        # Placeholder for configuring escalation policies. This functionality
        # would involve defining who to alert and when based on the severity
        # and duration of the detected pattern.
        logger.info(f"Escalation policies configured: {policies}")

if __name__ == '__main__':
    # Example usage (replace with actual configuration and alert triggers)
    logging.basicConfig(level=logging.INFO)
    config = {
        'email': {
            'enabled': False, # Set to True to enable email
            'sender_address': 'aiva@example.com',
            'recipient_address': 'admin@example.com',
            'smtp_server': 'smtp.example.com',
            'smtp_port': 587,
            'smtp_username': 'aiva',
            'smtp_password': 'password'
        },
        'slack': {
            'enabled': False, # Set to True to enable Slack
            'slack_webhook_url': 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
        },
        'alert_suppression_rules': [
            {
                'alert_type': 'HighCPULoad'
            }
        ]
    }

    alert_manager = AlertManager(config)

    # Simulate a downscale pattern detection
    alert_manager.send_alert(
        alert_type='HighCPULoad',
        message='CPU load exceeded 90% on server A.',
        details={'server': 'A', 'cpu_load': 95}
    )

    alert_manager.send_alert(
        alert_type='MemoryLeak',
        message='Memory leak detected in process X.',
        details={'process': 'X', 'memory_usage': '5GB'}
    )
