import psutil
import time
import threading

class ResourceMonitor:
    def __init__(self, interval=1.0):
        self.interval = interval
        self.data = []
        self.running = False
        self._thread = None

    def _monitor_loop(self):
        while self.running:
            cpu = psutil.cpu_percent(interval=None)
            memory = psutil.virtual_memory().percent
            self.data.append({
                'time': time.time(),
                'cpu_usage': cpu,
                'memory_usage': memory
            })
            time.sleep(self.interval)

    def start(self):
        self.running = True
        self.data = []
        self._thread = threading.Thread(target=self._monitor_loop, daemon=True)
        self._thread.start()

    def stop(self):
        self.running = False
        if self._thread:
            self._thread.join(timeout=2)
        return self.data

    def save_data(self, filename="resource_usage.csv"):
        import csv
        if not self.data:
            return
        
        keys = self.data[0].keys()
        with open(filename, 'w', newline='') as f:
            dict_writer = csv.DictWriter(f, fieldnames=keys)
            dict_writer.writeheader()
            dict_writer.writerows(self.data)
        print(f"Resource data saved to {filename}")
