import json
from PyQt6.QtCore import QTimer


class AutoFanStatus:
    def __init__(self, update_interval_ms=1000):
        self.cpu_temp = 0.0
        self.cpu_load = 0.0  # 1 分钟 CPU 负载
        self.fan_speed = 0
        self.fan_state = "Unknown"
        self.fan_rpm = 0
        self.is_auto_fan_service_running = False

        self._last_temp = 0.0
        self._same_counter = 0
        self._update_interval_ms = update_interval_ms
        self._timer = QTimer()
        self._timer.setSingleShot(False)
        self._timer.timeout.connect(self.update_status)
        self._timer.start(self._update_interval_ms)

    def update_status(self):
        try:
            with open("/dev/shm/fan_status.json", "r") as f:
                data = json.load(f)
                self.cpu_temp = data.get("temp", 0.0)
                self.fan_speed = data.get("pwm", 0)
                self.fan_state = "Stalled" if data.get("is_stalled", False) else "Running"
                self.fan_rpm = data.get("rpm", 0)
            if self.cpu_temp == self._last_temp:
                self._same_counter += 1
            else:
                self._same_counter = 0
                self._last_temp = self.cpu_temp
            self.is_auto_fan_service_running = self._same_counter < 5
        except (FileNotFoundError, json.JSONDecodeError, OSError):
            self.cpu_temp = 0.0
            self.fan_speed = 0
            self.fan_state = "Unknown"
            self.fan_rpm = 0
            self.is_auto_fan_service_running = False

        # 读取 CPU 负载（始终执行）
        try:
            with open("/proc/loadavg", "r") as f:
                fields = f.read().split()
                self.cpu_load = float(fields[0])  # 1 分钟平均负载
        except (OSError, IndexError, ValueError):
            self.cpu_load = 0.0