import logging

class DownscaleActions:
    def __init__(self, config):
        self.config = config
        self.logger = logging.getLogger(__name__)

    def execute_actions(self, pattern_name):
        actions = self.config.get(pattern_name, [])
        if not actions:
            self.logger.info(f"No actions defined for downscale pattern: {pattern_name}")
            return

        self.logger.info(f"Executing actions for downscale pattern: {pattern_name}")

        for action in actions:
            action_type = action.get('type')
            if action_type == 'log':
                self.log_action(action)
            elif action_type == 'alert':
                self.alert_action(action)
            elif action_type == 'scale':
                self.scale_action(action)
            else:
                self.logger.warning(f"Unknown action type: {action_type}")

    def log_action(self, action):
        message = action.get('message', 'Downscale detected.')
        level = action.get('level', 'info').lower()

        if level == 'info':
            self.logger.info(message)
        elif level == 'warning':
            self.logger.warning(message)
        elif level == 'error':
            self.logger.error(message)
        else:
            self.logger.warning(f"Invalid log level: {level}. Logging as info.")
            self.logger.info(message)

    def alert_action(self, action):
        alert_type = action.get('alert_type')
        details = action.get('details', {})

        if alert_type == 'email':
            self.send_email_alert(details)
        elif alert_type == 'slack':
            self.send_slack_alert(details)
        else:
            self.logger.warning(f"Unknown alert type: {alert_type}")

    def scale_action(self, action):
        policy_name = action.get('policy_name')
        # Simulate triggering a scaling policy
        self.logger.info(f"Simulating triggering scaling policy: {policy_name}")
        print(f"[SIMULATED] Triggering scaling policy: {policy_name}")  # Simulate scaling

    def send_email_alert(self, details):
        # Simulate sending an email alert
        recipient = details.get('recipient')
        subject = details.get('subject', 'Downscale Alert')
        body = details.get('body', 'Downscale detected and actions taken.')
        self.logger.info(f"[SIMULATED] Sending email to: {recipient} with subject: {subject}")
        print(f"[SIMULATED] Sending email to: {recipient} with subject: {subject}\nBody: {body}")

    def send_slack_alert(self, details):
        # Simulate sending a Slack alert
        channel = details.get('channel')
        message = details.get('message', 'Downscale detected and actions taken.')
        self.logger.info(f"[SIMULATED] Sending Slack message to channel: {channel}")
        print(f"[SIMULATED] Sending Slack message to channel: {channel}\nMessage: {message}")
