from aiva.logger import AIVALogger  # Import the logger

class ThresholdAnalyzer:
    def __init__(self, logger=None):
        self.thresholds = {}
        if logger is None:
            self.logger = AIVALogger()
        else:
            self.logger = logger

    def add_threshold(self, metric_name, threshold_type, threshold_value, scaling_action):
        if metric_name not in self.thresholds:
            self.thresholds[metric_name] = []
        self.thresholds[metric_name].append({
            'type': threshold_type,
            'value': threshold_value,
            'action': scaling_action
        })

    def analyze(self, metric_name, moving_average):
        if metric_name in self.thresholds:
            for threshold in self.thresholds[metric_name]:
                if threshold['type'] == 'Upper' and moving_average > threshold['value']:
                    self.logger.log_threshold_breach(metric_name, threshold['type'], threshold['value'], moving_average, threshold['action'])
                    self.logger.log_scaling_action_success(threshold['action'])
                    return threshold['action'] # Return the action to be taken
                elif threshold['type'] == 'Lower' and moving_average < threshold['value']:
                    self.logger.log_threshold_breach(metric_name, threshold['type'], threshold['value'], moving_average, threshold['action'])
                    self.logger.log_scaling_action_success(threshold['action'])
                    return threshold['action'] # Return the action to be taken
        return None # No action needed

# Example usage (for testing):
if __name__ == '__main__':
    logger = AIVALogger()
    analyzer = ThresholdAnalyzer(logger)
    analyzer.add_threshold('CPU_Usage', 'Upper', 90, 'Increase CPU Cores')
    analyzer.add_threshold('Memory_Usage', 'Upper', 95, 'Increase RAM')
    analyzer.add_threshold('Disk_Space', 'Lower', 10, 'Increase Disk Space')

    action = analyzer.analyze('CPU_Usage', 92)
    if action:
        print(f"Scaling action triggered: {action}")
    else:
        print("No scaling action needed.")

    action = analyzer.analyze('Memory_Usage', 98)
    if action:
        print(f"Scaling action triggered: {action}")
    else:
        print("No scaling action needed.")

    action = analyzer.analyze('Disk_Space', 5)
    if action:
        print(f"Scaling action triggered: {action}")
    else:
        print("No scaling action needed.")

    action = analyzer.analyze('Network_Latency', 50)
    if action:
        print(f"Scaling action triggered: {action}")
    else:
        print("No scaling action needed.")
