import logging
import time

logger = logging.getLogger(__name__)

class WorkloadAnalyzer:
    def __init__(self, config):
        self.config = config
        self.cpu_load_history = []
        self.last_analyzed_at = None

    def analyze(self, cpu_load):
        self.cpu_load_history.append(cpu_load)

        # Keep only the last N data points for analysis
        if len(self.cpu_load_history) > self.config.workload_history_size:
            self.cpu_load_history = self.cpu_load_history[-self.config.workload_history_size:]

        volatility = self.calculate_volatility()
        burstiness = self.calculate_burstiness()

        if self.config.enable_workload_logging and (self.last_analyzed_at is None or (time.time() - self.last_analyzed_at) > self.config.workload_log_interval):
            logger.info(f"[WORKLOAD LOG] Volatility: {volatility}, Burstiness: {burstiness}, CPU Load: {cpu_load}")
            self.last_analyzed_at = time.time()

        return volatility, burstiness

    def calculate_volatility(self):
        if len(self.cpu_load_history) < 2:
            return 0  # Not enough data
        # Calculate the standard deviation as a measure of volatility
        import numpy as np
        return np.std(self.cpu_load_history)

    def calculate_burstiness(self):
        if len(self.cpu_load_history) < 2:
            return 0  # Not enough data

        # Calculate the rate of change in CPU load
        changes = [self.cpu_load_history[i] - self.cpu_load_history[i-1] for i in range(1, len(self.cpu_load_history))]
        # Return the average absolute change as a measure of burstiness
        return sum(abs(change) for change in changes) / len(changes)
