import psutil
import time
import threading
from collections import deque
from aiva.config import settings

class CPUMonitor:
    def __init__(self):
        self.interval = settings.CPU_MONITOR_INTERVAL  # seconds
        self.window = settings.CPU_MONITOR_WINDOW  # seconds
        self.data = deque(maxlen=int(self.window / self.interval))
        self.running = False
        self.lock = threading.Lock()

    def start(self):
        self.running = True
        self.thread = threading.Thread(target=self._run)
        self.thread.daemon = True  # Allow the main thread to exit even if this is running
        self.thread.start()

    def stop(self):
        self.running = False
        self.thread.join()

    def _run(self):
        while self.running:
            cpu_usage = psutil.cpu_percent(interval=self.interval)
            with self.lock:
                self.data.append(cpu_usage)
            time.sleep(self.interval)

    def get_average_cpu_usage(self):
        with self.lock:
            if not self.data:
                return 0.0
            return sum(self.data) / len(self.data)

# Example Usage (Illustrative; would normally be managed by a higher-level system):
# if __name__ == '__main__':
#     monitor = CPUMonitor()
#     monitor.start()
#     time.sleep(10)  # Collect data for 10 seconds
#     print(f"Average CPU Usage: {monitor.get_average_cpu_usage()}%")
#     monitor.stop()