"""
事件处理器模块
负责处理网络同步相关的事件
"""

import time
from typing import Dict, Any, List, Optional, Callable
import threading
import queue

class NetworkEvent:
    """网络事件类"""
    def __init__(self, event_type: str, data: Dict[str, Any], timestamp: float = None):
        self.event_type = event_type
        self.data = data
        self.timestamp = timestamp or time.time()
        self.handled = False
        self.processed = False

class EventHandler:
    """
    事件处理器
    负责处理网络同步相关的事件
    """
    
    def __init__(self, plugin):
        """
        初始化事件处理器
        
        Args:
            plugin: 网络同步插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 事件配置
        self.event_config = {
            "enable_event_queue": True,
            "max_queue_size": 1000,
            "enable_async_processing": True,
            "max_processing_threads": 4,
            "event_timeout": 30.0,
            "enable_event_filtering": True,
            "enable_event_prioritization": True,
            "enable_event_coalescing": True,
            "coalesce_time_window": 0.1,  # 100ms
            "enable_event_logging": True,
            "log_level": "INFO"
        }
        
        # 事件队列
        self.event_queue = queue.Queue(maxsize=self.event_config["max_queue_size"])
        self.priority_queue = queue.PriorityQueue()
        
        # 事件处理器映射
        self.event_handlers = {}
        
        # 事件监听器
        self.event_listeners = {}
        
        # 事件统计
        self.event_stats = {
            "events_received": 0,
            "events_processed": 0,
            "events_dropped": 0,
            "events_timed_out": 0,
            "handler_errors": 0,
            "async_tasks": 0,
            "coalesced_events": 0
        }
        
        # 事件合并缓存
        self.coalesce_cache = {}
        
        # 异步处理线程
        self.processing_threads = []
        self.running = False
        
        # 回调函数
        self.event_callbacks = {
            "event_received": [],
            "event_processed": [],
            "event_dropped": [],
            "event_error": []
        }
        
        # 时间戳记录
        self.last_event_time = 0.0
        self.last_processing_time = 0.0
        
        print("✓ 事件处理器已创建")
        
    def initialize(self) -> bool:
        """
        初始化事件处理器
        
        Returns:
            是否初始化成功
        """
        try:
            # 注册默认事件处理器
            self._register_default_handlers()
            
            self.initialized = True
            print("✓ 事件处理器初始化完成")
            return True
            
        except Exception as e:
            print(f"✗ 事件处理器初始化失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def enable(self) -> bool:
        """
        启用事件处理器
        
        Returns:
            是否启用成功
        """
        try:
            if not self.initialized:
                print("✗ 事件处理器未初始化")
                return False
                
            self.enabled = True
            self.running = True
            
            # 启动事件处理线程
            if self.event_config["enable_async_processing"]:
                thread_count = self.event_config["max_processing_threads"]
                for i in range(thread_count):
                    thread = threading.Thread(target=self._event_processing_loop, daemon=True, 
                                            name=f"EventProcessor-{i}")
                    self.processing_threads.append(thread)
                    thread.start()
                    
            print("✓ 事件处理器已启用")
            return True
            
        except Exception as e:
            print(f"✗ 事件处理器启用失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def disable(self):
        """禁用事件处理器"""
        try:
            self.enabled = False
            self.running = False
            
            # 等待处理线程结束
            for thread in self.processing_threads:
                if thread.is_alive():
                    thread.join(timeout=2.0)
                    
            self.processing_threads.clear()
            print("✓ 事件处理器已禁用")
            
        except Exception as e:
            print(f"✗ 事件处理器禁用失败: {e}")
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理事件处理器资源"""
        try:
            self.disable()
            self.event_handlers.clear()
            self.event_listeners.clear()
            self.event_callbacks.clear()
            self.coalesce_cache.clear()
            
            # 清空队列
            while not self.event_queue.empty():
                try:
                    self.event_queue.get_nowait()
                except queue.Empty:
                    break
                    
            while not self.priority_queue.empty():
                try:
                    self.priority_queue.get_nowait()
                except queue.Empty:
                    break
                    
            self.initialized = False
            print("✓ 事件处理器资源已清理")
            
        except Exception as e:
            print(f"✗ 事件处理器资源清理失败: {e}")
            import traceback
            traceback.print_exc()
            
    def update(self, dt: float):
        """
        更新事件处理器状态
        
        Args:
            dt: 时间增量
        """
        try:
            if not self.enabled:
                return
                
            current_time = time.time()
            self.last_processing_time = current_time
            
            # 清理过期的合并缓存
            self._cleanup_coalesce_cache(current_time)
            
        except Exception as e:
            print(f"✗ 事件处理器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _register_default_handlers(self):
        """注册默认事件处理器"""
        try:
            # 网络相关事件
            self.register_event_handler("network_connected", self._handle_network_connected)
            self.register_event_handler("network_disconnected", self._handle_network_disconnected)
            self.register_event_handler("network_error", self._handle_network_error)
            self.register_event_handler("network_data_received", self._handle_network_data_received)
            self.register_event_handler("network_data_sent", self._handle_network_data_sent)
            
            # 同步相关事件
            self.register_event_handler("object_synced", self._handle_object_synced)
            self.register_event_handler("sync_error", self._handle_sync_error)
            self.register_event_handler("interpolation_updated", self._handle_interpolation_updated)
            self.register_event_handler("extrapolation_updated", self._handle_extrapolation_updated)
            
            # 连接相关事件
            self.register_event_handler("client_connected", self._handle_client_connected)
            self.register_event_handler("client_disconnected", self._handle_client_disconnected)
            self.register_event_handler("connection_timeout", self._handle_connection_timeout)
            
            # 协议相关事件
            self.register_event_handler("message_received", self._handle_message_received)
            self.register_event_handler("message_sent", self._handle_message_sent)
            self.register_event_handler("protocol_error", self._handle_protocol_error)
            
            # 时钟相关事件
            self.register_event_handler("sync_started", self._handle_sync_started)
            self.register_event_handler("sync_completed", self._handle_sync_completed)
            self.register_event_handler("sync_failed", self._handle_sync_failed)
            self.register_event_handler("time_updated", self._handle_time_updated)
            self.register_event_handler("sync_quality_changed", self._handle_sync_quality_changed)
            
            # 配置相关事件
            self.register_event_handler("config_loaded", self._handle_config_loaded)
            self.register_event_handler("config_saved", self._handle_config_saved)
            self.register_event_handler("config_changed", self._handle_config_changed)
            self.register_event_handler("config_error", self._handle_config_error)
            
            # 序列化相关事件
            self.register_event_handler("data_serialized", self._handle_data_serialized)
            self.register_event_handler("data_deserialized", self._handle_data_deserialized)
            self.register_event_handler("serialization_error", self._handle_serialization_error)
            self.register_event_handler("deserialization_error", self._handle_deserialization_error)
            
            # 预测相关事件
            self.register_event_handler("prediction_updated", self._handle_prediction_updated)
            self.register_event_handler("correction_applied", self._handle_correction_applied)
            self.register_event_handler("snap_correction", self._handle_snap_correction)
            self.register_event_handler("prediction_error", self._handle_prediction_error)
            
            print("✓ 默认事件处理器已注册")
        except Exception as e:
            print(f"✗ 默认事件处理器注册失败: {e}")
            
    def _event_processing_loop(self):
        """事件处理循环"""
        try:
            while self.running:
                try:
                    # 优先处理优先级队列中的事件
                    try:
                        priority, event = self.priority_queue.get(timeout=0.01)
                        self._process_event(event)
                        self.priority_queue.task_done()
                    except queue.Empty:
                        # 处理普通队列中的事件
                        try:
                            event = self.event_queue.get(timeout=0.01)
                            self._process_event(event)
                            self.event_queue.task_done()
                        except queue.Empty:
                            # 没有事件，短暂休眠
                            time.sleep(0.001)
                            
                except Exception as e:
                    print(f"✗ 事件处理循环错误: {e}")
                    time.sleep(0.1)
                    
        except Exception as e:
            print(f"✗ 事件处理循环失败: {e}")
            
    def _process_event(self, event: NetworkEvent):
        """
        处理事件
        
        Args:
            event: 网络事件
        """
        try:
            current_time = time.time()
            
            # 检查事件是否超时
            if current_time - event.timestamp > self.event_config["event_timeout"]:
                self.event_stats["events_timed_out"] += 1
                self._trigger_event_callback("event_dropped", {
                    "event": event,
                    "reason": "timeout"
                })
                return
                
            # 查找事件处理器
            handler = self.event_handlers.get(event.event_type)
            if handler:
                try:
                    # 调用事件处理器
                    result = handler(event.data)
                    event.processed = True
                    
                    # 更新统计信息
                    self.event_stats["events_processed"] += 1
                    
                    # 触发事件处理完成回调
                    self._trigger_event_callback("event_processed", {
                        "event": event,
                        "result": result,
                        "processing_time": time.time() - event.timestamp
                    })
                    
                except Exception as e:
                    print(f"✗ 事件处理器执行失败: {event.event_type} - {e}")
                    self.event_stats["handler_errors"] += 1
                    
                    # 触发事件错误回调
                    self._trigger_event_callback("event_error", {
                        "event": event,
                        "error": str(e)
                    })
            else:
                # 没有找到处理器，但仍标记为已处理
                event.processed = True
                self.event_stats["events_processed"] += 1
                
                # 触发事件处理完成回调
                self._trigger_event_callback("event_processed", {
                    "event": event,
                    "result": None,
                    "processing_time": time.time() - event.timestamp
                })
                
        except Exception as e:
            print(f"✗ 事件处理失败: {e}")
            
    def post_event(self, event_type: str, data: Dict[str, Any] = None, 
                   priority: int = 0, timestamp: float = None) -> bool:
        """
        发布事件
        
        Args:
            event_type: 事件类型
            data: 事件数据
            priority: 事件优先级（数字越小优先级越高）
            timestamp: 事件时间戳
            
        Returns:
            是否发布成功
        """
        try:
            if not self.enabled:
                print("✗ 事件处理器未启用")
                return False
                
            # 创建事件对象
            event = NetworkEvent(event_type, data or {}, timestamp)
            
            # 触发事件接收回调
            self._trigger_event_callback("event_received", {
                "event": event
            })
            
            # 检查事件合并
            if self.event_config["enable_event_coalescing"]:
                if self._coalesce_event(event):
                    # 事件已合并，不需要添加到队列
                    return True
                    
            # 添加到相应队列
            if priority > 0 and self.event_config["enable_event_prioritization"]:
                # 添加到优先级队列
                try:
                    self.priority_queue.put((priority, event), timeout=0.1)
                except queue.Full:
                    self.event_stats["events_dropped"] += 1
                    self._trigger_event_callback("event_dropped", {
                        "event": event,
                        "reason": "priority_queue_full"
                    })
                    return False
            else:
                # 添加到普通队列
                try:
                    self.event_queue.put(event, timeout=0.1)
                except queue.Full:
                    self.event_stats["events_dropped"] += 1
                    self._trigger_event_callback("event_dropped", {
                        "event": event,
                        "reason": "queue_full"
                    })
                    return False
                    
            self.event_stats["events_received"] += 1
            self.last_event_time = event.timestamp
            
            return True
            
        except Exception as e:
            print(f"✗ 事件发布失败: {e}")
            return False
            
    def _coalesce_event(self, event: NetworkEvent) -> bool:
        """
        合并事件
        
        Args:
            event: 网络事件
            
        Returns:
            是否合并成功
        """
        try:
            if not self.event_config["enable_event_coalescing"]:
                return False
                
            current_time = time.time()
            coalesce_key = f"{event.event_type}_{hash(str(event.data))}"
            
            # 检查是否在合并时间窗口内
            if coalesce_key in self.coalesce_cache:
                cached_event, cache_time = self.coalesce_cache[coalesce_key]
                if current_time - cache_time < self.event_config["coalesce_time_window"]:
                    # 合并事件
                    self.event_stats["coalesced_events"] += 1
                    return True
                    
            # 缓存事件
            self.coalesce_cache[coalesce_key] = (event, current_time)
            return False
            
        except Exception as e:
            print(f"✗ 事件合并失败: {e}")
            return False
            
    def _cleanup_coalesce_cache(self, current_time: float):
        """
        清理合并缓存
        
        Args:
            current_time: 当前时间
        """
        try:
            expired_keys = [
                key for key, (_, cache_time) in self.coalesce_cache.items()
                if current_time - cache_time > self.event_config["coalesce_time_window"] * 2
            ]
            
            for key in expired_keys:
                del self.coalesce_cache[key]
                
        except Exception as e:
            print(f"✗ 合并缓存清理失败: {e}")
            
    def register_event_handler(self, event_type: str, handler: Callable) -> bool:
        """
        注册事件处理器
        
        Args:
            event_type: 事件类型
            handler: 处理器函数
            
        Returns:
            是否注册成功
        """
        try:
            self.event_handlers[event_type] = handler
            print(f"✓ 事件处理器已注册: {event_type}")
            return True
        except Exception as e:
            print(f"✗ 事件处理器注册失败: {e}")
            return False
            
    def unregister_event_handler(self, event_type: str) -> bool:
        """
        注销事件处理器
        
        Args:
            event_type: 事件类型
            
        Returns:
            是否注销成功
        """
        try:
            if event_type in self.event_handlers:
                del self.event_handlers[event_type]
                print(f"✓ 事件处理器已注销: {event_type}")
                return True
            else:
                print(f"✗ 事件处理器不存在: {event_type}")
                return False
        except Exception as e:
            print(f"✗ 事件处理器注销失败: {e}")
            return False
            
    def register_event_listener(self, event_type: str, listener: Callable) -> bool:
        """
        注册事件监听器
        
        Args:
            event_type: 事件类型
            listener: 监听器函数
            
        Returns:
            是否注册成功
        """
        try:
            if event_type not in self.event_listeners:
                self.event_listeners[event_type] = []
                
            self.event_listeners[event_type].append(listener)
            print(f"✓ 事件监听器已注册: {event_type}")
            return True
        except Exception as e:
            print(f"✗ 事件监听器注册失败: {e}")
            return False
            
    def unregister_event_listener(self, event_type: str, listener: Callable) -> bool:
        """
        注销事件监听器
        
        Args:
            event_type: 事件类型
            listener: 监听器函数
            
        Returns:
            是否注销成功
        """
        try:
            if event_type in self.event_listeners:
                if listener in self.event_listeners[event_type]:
                    self.event_listeners[event_type].remove(listener)
                    print(f"✓ 事件监听器已注销: {event_type}")
                    return True
                    
            print(f"✗ 事件监听器不存在: {event_type}")
            return False
        except Exception as e:
            print(f"✗ 事件监听器注销失败: {e}")
            return False
            
    # 默认事件处理器
    def _handle_network_connected(self, data: Dict[str, Any]) -> bool:
        """处理网络连接事件"""
        try:
            print(f"✓ 网络已连接: {data}")
            
            # 更新连接状态
            if self.plugin.connection_manager:
                self.plugin.connection_manager.client_state["is_connected"] = True
                self.plugin.connection_manager.client_state["connection_time"] = time.time()
                
            return True
        except Exception as e:
            print(f"✗ 网络连接事件处理失败: {e}")
            return False
            
    def _handle_network_disconnected(self, data: Dict[str, Any]) -> bool:
        """处理网络断开事件"""
        try:
            print(f"✓ 网络已断开: {data}")
            
            # 更新连接状态
            if self.plugin.connection_manager:
                self.plugin.connection_manager.client_state["is_connected"] = False
                self.plugin.connection_manager.client_state["connection_time"] = 0.0
                
            return True
        except Exception as e:
            print(f"✗ 网络断开事件处理失败: {e}")
            return False
            
    def _handle_network_error(self, data: Dict[str, Any]) -> bool:
        """处理网络错误事件"""
        try:
            print(f"✗ 网络错误: {data}")
            
            # 记录错误统计
            self.event_stats["handler_errors"] += 1
            
            return True
        except Exception as e:
            print(f"✗ 网络错误事件处理失败: {e}")
            return False
            
    def _handle_network_data_received(self, data: Dict[str, Any]) -> bool:
        """处理网络数据接收事件"""
        try:
            # 将数据传递给协议处理器
            if self.plugin.protocol_handler:
                self.plugin.protocol_handler.receive_message(data.get("message_data", b""))
                
            return True
        except Exception as e:
            print(f"✗ 网络数据接收事件处理失败: {e}")
            return False
            
    def _handle_network_data_sent(self, data: Dict[str, Any]) -> bool:
        """处理网络数据发送事件"""
        try:
            # 可以在这里添加发送确认逻辑
            return True
        except Exception as e:
            print(f"✗ 网络数据发送事件处理失败: {e}")
            return False
            
    def _handle_object_synced(self, data: Dict[str, Any]) -> bool:
        """处理对象同步事件"""
        try:
            object_id = data.get("object_id")
            object_data = data.get("object_data")
            
            # 更新对象状态
            if self.plugin.object_sync and object_id and object_data:
                self.plugin.object_sync.update_object(object_id, object_data)
                
            return True
        except Exception as e:
            print(f"✗ 对象同步事件处理失败: {e}")
            return False
            
    def _handle_sync_error(self, data: Dict[str, Any]) -> bool:
        """处理同步错误事件"""
        try:
            print(f"✗ 同步错误: {data}")
            
            # 记录错误统计
            self.event_stats["handler_errors"] += 1
            
            return True
        except Exception as e:
            print(f"✗ 同步错误事件处理失败: {e}")
            return False
            
    def _handle_interpolation_updated(self, data: Dict[str, Any]) -> bool:
        """处理插值更新事件"""
        try:
            # 可以在这里添加插值更新后的处理逻辑
            return True
        except Exception as e:
            print(f"✗ 插值更新事件处理失败: {e}")
            return False
            
    def _handle_extrapolation_updated(self, data: Dict[str, Any]) -> bool:
        """处理外推更新事件"""
        try:
            # 可以在这里添加外推更新后的处理逻辑
            return True
        except Exception as e:
            print(f"✗ 外推更新事件处理失败: {e}")
            return False
            
    def _handle_client_connected(self, data: Dict[str, Any]) -> bool:
        """处理客户端连接事件"""
        try:
            client_id = data.get("client_id")
            address = data.get("address")
            
            print(f"✓ 客户端已连接: {client_id} ({address})")
            
            # 添加到连接管理器
            if self.plugin.connection_manager and client_id and address:
                # 这里需要访问socket对象，简化处理
                pass
                
            return True
        except Exception as e:
            print(f"✗ 客户端连接事件处理失败: {e}")
            return False
            
    def _handle_client_disconnected(self, data: Dict[str, Any]) -> bool:
        """处理客户端断开事件"""
        try:
            client_id = data.get("client_id")
            reason = data.get("reason", "unknown")
            
            print(f"✓ 客户端已断开: {client_id} (原因: {reason})")
            
            # 从连接管理器移除
            if self.plugin.connection_manager and client_id:
                self.plugin.connection_manager.remove_client(client_id, reason)
                
            return True
        except Exception as e:
            print(f"✗ 客户端断开事件处理失败: {e}")
            return False
            
    def _handle_connection_timeout(self, data: Dict[str, Any]) -> bool:
        """处理连接超时事件"""
        try:
            client_id = data.get("client_id")
            
            print(f"✓ 连接超时: {client_id}")
            
            # 断开超时连接
            if self.plugin.connection_manager and client_id:
                self.plugin.connection_manager.remove_client(client_id, "timeout")
                
            return True
        except Exception as e:
            print(f"✗ 连接超时事件处理失败: {e}")
            return False
            
    def _handle_message_received(self, data: Dict[str, Any]) -> bool:
        """处理消息接收事件"""
        try:
            message_type = data.get("type")
            message_data = data.get("data")
            
            print(f"✓ 消息已接收: {message_type}")
            
            # 根据消息类型处理
            if message_type == "sync_data":
                # 处理同步数据
                if self.plugin.object_sync and message_data:
                    for obj_id, obj_data in message_data.items():
                        self.plugin.object_sync.receive_sync_data(obj_id, obj_data)
                        
            elif message_type == "heartbeat":
                # 处理心跳包
                if self.plugin.connection_manager:
                    # 需要client_id来处理心跳
                    pass
                    
            return True
        except Exception as e:
            print(f"✗ 消息接收事件处理失败: {e}")
            return False
            
    def _handle_message_sent(self, data: Dict[str, Any]) -> bool:
        """处理消息发送事件"""
        try:
            message_type = data.get("type")
            fragmented = data.get("fragmented", False)
            
            print(f"✓ 消息已发送: {message_type} ({'分片' if fragmented else '完整'})")
            
            return True
        except Exception as e:
            print(f"✗ 消息发送事件处理失败: {e}")
            return False
            
    def _handle_protocol_error(self, data: Dict[str, Any]) -> bool:
        """处理协议错误事件"""
        try:
            error = data.get("error", "Unknown protocol error")
            print(f"✗ 协议错误: {error}")
            
            # 记录错误统计
            self.event_stats["handler_errors"] += 1
            
            return True
        except Exception as e:
            print(f"✗ 协议错误事件处理失败: {e}")
            return False
            
    def _handle_sync_started(self, data: Dict[str, Any]) -> bool:
        """处理同步开始事件"""
        try:
            print("✓ 时钟同步已开始")
            return True
        except Exception as e:
            print(f"✗ 同步开始事件处理失败: {e}")
            return False
            
    def _handle_sync_completed(self, data: Dict[str, Any]) -> bool:
        """处理同步完成事件"""
        try:
            offset = data.get("offset", 0.0)
            rtt = data.get("rtt", 0.0)
            quality = data.get("quality", 0.0)
            
            print(f"✓ 时钟同步已完成 - 偏移: {offset:.3f}s, RTT: {rtt:.3f}s, 质量: {quality:.2f}")
            
            return True
        except Exception as e:
            print(f"✗ 同步完成事件处理失败: {e}")
            return False
            
    def _handle_sync_failed(self, data: Dict[str, Any]) -> bool:
        """处理同步失败事件"""
        try:
            reason = data.get("reason", "unknown")
            error = data.get("error", "")
            
            print(f"✗ 时钟同步失败 - 原因: {reason}, 错误: {error}")
            
            # 记录错误统计
            self.event_stats["handler_errors"] += 1
            
            return True
        except Exception as e:
            print(f"✗ 同步失败事件处理失败: {e}")
            return False
            
    def _handle_time_updated(self, data: Dict[str, Any]) -> bool:
        """处理时间更新事件"""
        try:
            server_time = data.get("server_time", 0.0)
            interpolated_time = data.get("interpolated_time", 0.0)
            
            # 可以在这里添加时间更新后的处理逻辑
            return True
        except Exception as e:
            print(f"✗ 时间更新事件处理失败: {e}")
            return False
            
    def _handle_sync_quality_changed(self, data: Dict[str, Any]) -> bool:
        """处理同步质量变化事件"""
        try:
            quality = data.get("quality", 0.0)
            offset = data.get("offset", 0.0)
            rtt = data.get("rtt", 0.0)
            
            print(f"✓ 同步质量变化 - 质量: {quality:.2f}, 偏移: {offset:.3f}s, RTT: {rtt:.3f}s")
            
            return True
        except Exception as e:
            print(f"✗ 同步质量变化事件处理失败: {e}")
            return False
            
    def _handle_config_loaded(self, data: Dict[str, Any]) -> bool:
        """处理配置加载事件"""
        try:
            config = data.get("config", {})
            timestamp = data.get("timestamp", 0.0)
            
            print(f"✓ 配置已加载 - 时间: {timestamp}")
            
            # 应用配置到各个模块
            if self.plugin.config_manager:
                self.plugin.config_manager.apply_config_to_modules()
                
            return True
        except Exception as e:
            print(f"✗ 配置加载事件处理失败: {e}")
            return False
            
    def _handle_config_saved(self, data: Dict[str, Any]) -> bool:
        """处理配置保存事件"""
        try:
            config = data.get("config", {})
            timestamp = data.get("timestamp", 0.0)
            
            print(f"✓ 配置已保存 - 时间: {timestamp}")
            
            return True
        except Exception as e:
            print(f"✗ 配置保存事件处理失败: {e}")
            return False
            
    def _handle_config_changed(self, data: Dict[str, Any]) -> bool:
        """处理配置变更事件"""
        try:
            section = data.get("section")
            key = data.get("key")
            old_value = data.get("old_value")
            new_value = data.get("new_value")
            
            print(f"✓ 配置已变更 - {section}.{key}: {old_value} -> {new_value}")
            
            # 应用配置变更到相应模块
            if self.plugin.config_manager:
                self.plugin.config_manager.apply_config_to_modules()
                
            return True
        except Exception as e:
            print(f"✗ 配置变更事件处理失败: {e}")
            return False
            
    def _handle_config_error(self, data: Dict[str, Any]) -> bool:
        """处理配置错误事件"""
        try:
            error = data.get("error", "Unknown config error")
            operation = data.get("operation", "unknown")
            
            print(f"✗ 配置错误 - 操作: {operation}, 错误: {error}")
            
            # 记录错误统计
            self.event_stats["handler_errors"] += 1
            
            return True
        except Exception as e:
            print(f"✗ 配置错误事件处理失败: {e}")
            return False
            
    def _handle_data_serialized(self, data: Dict[str, Any]) -> bool:
        """处理数据序列化事件"""
        try:
            format = data.get("format", "unknown")
            size = data.get("size", 0)
            cached = data.get("cached", False)
            
            print(f"✓ 数据已序列化 - 格式: {format}, 大小: {size}字节 ({'缓存' if cached else '新'})")
            
            return True
        except Exception as e:
            print(f"✗ 数据序列化事件处理失败: {e}")
            return False
            
    def _handle_data_deserialized(self, data: Dict[str, Any]) -> bool:
        """处理数据反序列化事件"""
        try:
            format = data.get("format", "unknown")
            size = data.get("size", 0)
            
            print(f"✓ 数据已反序列化 - 格式: {format}, 大小: {size}字节")
            
            return True
        except Exception as e:
            print(f"✗ 数据反序列化事件处理失败: {e}")
            return False
            
    def _handle_serialization_error(self, data: Dict[str, Any]) -> bool:
        """处理序列化错误事件"""
        try:
            error = data.get("error", "Unknown serialization error")
            
            print(f"✗ 序列化错误: {error}")
            
            # 记录错误统计
            self.event_stats["handler_errors"] += 1
            
            return True
        except Exception as e:
            print(f"✗ 序列化错误事件处理失败: {e}")
            return False
            
    def _handle_deserialization_error(self, data: Dict[str, Any]) -> bool:
        """处理反序列化错误事件"""
        try:
            error = data.get("error", "Unknown deserialization error")
            
            print(f"✗ 反序列化错误: {error}")
            
            # 记录错误统计
            self.event_stats["handler_errors"] += 1
            
            return True
        except Exception as e:
            print(f"✗ 反序列化错误事件处理失败: {e}")
            return False
            
    def _handle_prediction_updated(self, data: Dict[str, Any]) -> bool:
        """处理预测更新事件"""
        try:
            object_id = data.get("object_id")
            prediction_time = data.get("prediction_time", 0.0)
            
            print(f"✓ 预测已更新 - 对象: {object_id}, 时间: {prediction_time:.3f}")
            
            return True
        except Exception as e:
            print(f"✗ 预测更新事件处理失败: {e}")
            return False
            
    def _handle_correction_applied(self, data: Dict[str, Any]) -> bool:
        """处理校正应用事件"""
        try:
            object_id = data.get("object_id")
            error = data.get("error", 0.0)
            
            print(f"✓ 校正已应用 - 对象: {object_id}, 误差: {error:.3f}")
            
            return True
        except Exception as e:
            print(f"✗ 校正应用事件处理失败: {e}")
            return False
            
    def _handle_snap_correction(self, data: Dict[str, Any]) -> bool:
        """处理快照校正事件"""
        try:
            object_id = data.get("object_id")
            error = data.get("error", 0.0)
            
            print(f"✓ 快照校正 - 对象: {object_id}, 误差: {error:.3f}")
            
            return True
        except Exception as e:
            print(f"✗ 快照校正事件处理失败: {e}")
            return False
            
    def _handle_prediction_error(self, data: Dict[str, Any]) -> bool:
        """处理预测错误事件"""
        try:
            object_id = data.get("object_id")
            error = data.get("error", "")
            
            print(f"✗ 预测错误 - 对象: {object_id}, 错误: {error}")
            
            # 记录错误统计
            self.event_stats["handler_errors"] += 1
            
            return True
        except Exception as e:
            print(f"✗ 预测错误事件处理失败: {e}")
            return False
            
    def get_event_stats(self) -> Dict[str, int]:
        """
        获取事件统计信息
        
        Returns:
            事件统计字典
        """
        return self.event_stats.copy()
        
    def reset_event_stats(self):
        """重置事件统计信息"""
        try:
            self.event_stats = {
                "events_received": 0,
                "events_processed": 0,
                "events_dropped": 0,
                "events_timed_out": 0,
                "handler_errors": 0,
                "async_tasks": 0,
                "coalesced_events": 0
            }
            print("✓ 事件统计信息已重置")
        except Exception as e:
            print(f"✗ 事件统计信息重置失败: {e}")
            
    def set_event_config(self, config: Dict[str, Any]) -> bool:
        """
        设置事件配置
        
        Args:
            config: 事件配置字典
            
        Returns:
            是否设置成功
        """
        try:
            self.event_config.update(config)
            print(f"✓ 事件配置已更新: {self.event_config}")
            return True
        except Exception as e:
            print(f"✗ 事件配置设置失败: {e}")
            return False
            
    def get_event_config(self) -> Dict[str, Any]:
        """
        获取事件配置
        
        Returns:
            事件配置字典
        """
        return self.event_config.copy()
        
    def _trigger_event_callback(self, callback_type: str, data: Dict[str, Any]):
        """
        触发事件回调
        
        Args:
            callback_type: 回调类型
            data: 回调数据
        """
        try:
            if callback_type in self.event_callbacks:
                for callback in self.event_callbacks[callback_type]:
                    try:
                        callback(data)
                    except Exception as e:
                        print(f"✗ 事件回调执行失败: {e}")
        except Exception as e:
            print(f"✗ 事件回调触发失败: {e}")
            
    def register_event_callback(self, callback_type: str, callback: Callable):
        """
        注册事件回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.event_callbacks:
                self.event_callbacks[callback_type].append(callback)
                print(f"✓ 事件回调已注册: {callback_type}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 事件回调注册失败: {e}")
            
    def unregister_event_callback(self, callback_type: str, callback: Callable):
        """
        注销事件回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.event_callbacks:
                if callback in self.event_callbacks[callback_type]:
                    self.event_callbacks[callback_type].remove(callback)
                    print(f"✓ 事件回调已注销: {callback_type}")
        except Exception as e:
            print(f"✗ 事件回调注销失败: {e}")
            
    def clear_event_queue(self):
        """清空事件队列"""
        try:
            # 清空普通队列
            while not self.event_queue.empty():
                try:
                    self.event_queue.get_nowait()
                except queue.Empty:
                    break
                    
            # 清空优先级队列
            while not self.priority_queue.empty():
                try:
                    self.priority_queue.get_nowait()
                except queue.Empty:
                    break
                    
            print("✓ 事件队列已清空")
        except Exception as e:
            print(f"✗ 事件队列清空失败: {e}")
            
    def get_queue_size(self) -> Dict[str, int]:
        """
        获取队列大小
        
        Returns:
            队列大小字典
        """
        return {
            "event_queue": self.event_queue.qsize(),
            "priority_queue": self.priority_queue.qsize()
        }