import time
from collections import deque
from aiva.utils import math_utils

class MetricAnalyzer:
    def __init__(self, window_size=5):  # Window size in minutes
        self.window_size = window_size * 60  # Convert to seconds
        self.cpu_utilization_queue = deque()
        self.memory_utilization_queue = deque()
        self.network_io_queue = deque()

    def analyze_metrics(self, cpu_utilization, memory_utilization, network_io):
        timestamp = time.time()

        # Add new metrics to the queues
        self.cpu_utilization_queue.append((timestamp, cpu_utilization))
        self.memory_utilization_queue.append((timestamp, memory_utilization))
        self.network_io_queue.append((timestamp, network_io))

        # Clean up old metrics outside the window
        self._clean_queue(self.cpu_utilization_queue, timestamp)
        self._clean_queue(self.memory_utilization_queue, timestamp)
        self._clean_queue(self.network_io_queue, timestamp)

        # Calculate moving averages
        cpu_moving_average = math_utils.calculate_moving_average(self.cpu_utilization_queue)
        memory_moving_average = math_utils.calculate_moving_average(self.memory_utilization_queue)
        network_io_moving_average = math_utils.calculate_moving_average(self.network_io_queue)

        return {
            "cpu_utilization": cpu_utilization,
            "cpu_moving_average": cpu_moving_average,
            "memory_utilization": memory_utilization,
            "memory_moving_average": memory_moving_average,
            "network_io": network_io,
            "network_io_moving_average": network_io_moving_average
        }

    def _clean_queue(self, queue, current_time):
        while queue and current_time - queue[0][0] > self.window_size:
            queue.popleft()
