import json
import os
from PyQt6.QtCore import QObject, pyqtSignal, QFileSystemWatcher


class ConfigParse(QObject):
    """配置文件解析与自动重载"""
    config_changed = pyqtSignal(object)  # 发送自身实例

    def __init__(self, config_file="config.json"):
        super().__init__()
        self.config_file = config_file
        self.api_url = None
        self.api_key = None
        self.gcode_dir = None
        self.move_axis_area = None
        self.move_max_speed = None
        self.config = self._load_config()
        self._parse_config()

        # 使用 QFileSystemWatcher 监视文件变化
        self._watcher = QFileSystemWatcher(self)
        self._watch_path = os.path.abspath(self.config_file)
        self._last_mtime = 0
        self._start_watching()

    def _start_watching(self):
        """启动文件监视"""
        if not os.path.isfile(self._watch_path):
            return
        self._last_mtime = os.path.getmtime(self._watch_path)
        if self._watch_path not in self._watcher.files():
            self._watcher.addPath(self._watch_path)
        self._watcher.fileChanged.connect(self._on_file_changed)

    def _on_file_changed(self, path):
        """文件变化时重新加载（防止保存中多次触发，用 mtime 去抖动）"""
        try:
            mtime = os.path.getmtime(path)
            if mtime <= self._last_mtime:
                return
            self._last_mtime = mtime
        except OSError:
            return

        old_config = self.config
        new_config = self._load_config()
        if new_config == old_config:
            return

        self.config = new_config
        self._parse_config()
        self.config_changed.emit(self)

    def _load_config(self):
        try:
            with open(self.config_file, "r") as f:
                return json.load(f)
        except Exception as e:
            print(f"Error loading config: {e}")
            return {}

    def _parse_config(self):
        self.api_url = self.config.get("api_url", None)
        self.api_key = self.config.get("api_key", None)
        self.gcode_dir = self.config.get("gcode_dir", None)
        self.move_axis_area = self.config.get("move_axis_area", None)
        self.move_max_speed = self.config.get("move_max_speed", {"x": 3000, "y": 3000, "z": 200})
        self.home_positions = self.config.get("home_positions", {"x": 134, "y": 123, "z": 10})
        self.move_max_speed = self.config.get("move_max_speed", None)