"""
事件处理器模块
处理通信事件和系统响应
"""

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

class EventHandler:
    """
    事件处理器
    处理通信事件和系统响应
    """
    
    def __init__(self, plugin):
        """
        初始化事件处理器
        
        Args:
            plugin: 实时通信插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 事件配置
        self.event_config = {
            "enable_event_system": True,
            "max_event_queue_size": 10000,
            "enable_event_filtering": True,
            "event_processing_interval": 0.01,  # 10ms
            "enable_async_processing": True,
            "max_concurrent_events": 100,
            "enable_event_prioritization": True,
            "enable_event_logging": True
        }
        
        # 事件状态
        self.event_state = {
            "is_processing": False,
            "pending_events": 0,
            "processed_events": 0,
            "dropped_events": 0,
            "last_event_time": 0.0
        }
        
        # 事件队列
        self.event_queue = queue.Queue(maxsize=self.event_config["max_event_queue_size"])
        self.event_queue_lock = threading.RLock()
        
        # 事件处理器存储
        self.event_handlers = {}
        
        # 事件统计
        self.event_stats = {
            "events_received": 0,
            "events_processed": 0,
            "events_dropped": 0,
            "handler_errors": 0,
            "async_events": 0
        }
        
        # 事件过滤器
        self.event_filters = {}
        
        # 回调函数
        self.event_callbacks = {
            "event_received": [],
            "event_processed": [],
            "event_dropped": [],
            "event_error": []
        }
        
        # 事件处理线程
        self.event_thread = None
        self.event_thread_running = False
        
        # 时间戳记录
        self.last_event_process = 0.0
        self.last_stats_reset = 0.0
        
        print("✓ 事件处理器已创建")
        
    def initialize(self) -> bool:
        """
        初始化事件处理器
        
        Returns:
            是否初始化成功
        """
        try:
            print("正在初始化事件处理器...")
            
            # 注册默认事件处理器
            self._register_default_handlers()
            
            # 启动事件处理线程
            self._start_event_thread()
            
            self.initialized = True
            print("✓ 事件处理器初始化完成")
            return True
            
        except Exception as e:
            print(f"✗ 事件处理器初始化失败: {e}")
            self.event_stats["handler_errors"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def _register_default_handlers(self):
        """注册默认事件处理器"""
        try:
            # 注册系统事件处理器
            self.register_event_handler("client_connected", self._handle_client_connected)
            self.register_event_handler("client_disconnected", self._handle_client_disconnected)
            self.register_event_handler("message_received", self._handle_message_received)
            self.register_event_handler("room_created", self._handle_room_created)
            self.register_event_handler("room_destroyed", self._handle_room_destroyed)
            self.register_event_handler("client_joined_room", self._handle_client_joined_room)
            self.register_event_handler("client_left_room", self._handle_client_left_room)
            
            print("✓ 默认事件处理器已注册")
            
        except Exception as e:
            print(f"✗ 默认事件处理器注册失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def _start_event_thread(self):
        """启动事件处理线程"""
        try:
            self.event_thread_running = True
            self.event_thread = threading.Thread(target=self._event_loop, daemon=True)
            self.event_thread.start()
            print("✓ 事件处理线程已启动")
        except Exception as e:
            print(f"✗ 事件处理线程启动失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def _event_loop(self):
        """事件处理循环"""
        try:
            while self.event_thread_running:
                try:
                    if self.enabled and self.event_config["enable_event_system"]:
                        # 处理事件队列
                        self._process_event_queue()
                        
                    # 短暂休眠
                    time.sleep(self.event_config["event_processing_interval"])
                    
                except Exception as e:
                    print(f"✗ 事件处理循环错误: {e}")
                    self.event_stats["handler_errors"] += 1
                    time.sleep(1.0)  # 出错时延长休眠
                    
        except Exception as e:
            print(f"✗ 事件处理线程失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def enable(self) -> bool:
        """
        启用事件处理器
        
        Returns:
            是否启用成功
        """
        try:
            if not self.initialized:
                print("✗ 事件处理器未初始化")
                return False
                
            self.enabled = True
            print("✓ 事件处理器已启用")
            return True
            
        except Exception as e:
            print(f"✗ 事件处理器启用失败: {e}")
            self.event_stats["handler_errors"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def disable(self):
        """禁用事件处理器"""
        try:
            self.enabled = False
            
            # 停止事件处理线程
            if self.event_thread_running:
                self.event_thread_running = False
                if self.event_thread and self.event_thread.is_alive():
                    self.event_thread.join(timeout=5.0)
                    
            print("✓ 事件处理器已禁用")
            
        except Exception as e:
            print(f"✗ 事件处理器禁用失败: {e}")
            self.event_stats["handler_errors"] += 1
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理事件处理器资源"""
        try:
            # 禁用事件处理器
            if self.enabled:
                self.disable()
                
            # 清理回调和处理器
            self.event_callbacks.clear()
            self.event_handlers.clear()
            self.event_filters.clear()
            
            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.event_state["last_event_time"] = current_time
            
        except Exception as e:
            print(f"✗ 事件处理器更新失败: {e}")
            self.event_stats["handler_errors"] += 1
            import traceback
            traceback.print_exc()
            
    def _process_event_queue(self):
        """处理事件队列"""
        try:
            processed_count = 0
            max_process_per_loop = 100  # 每次循环最多处理100个事件
            
            while not self.event_queue.empty() and processed_count < max_process_per_loop:
                try:
                    # 从队列获取事件
                    event_data = self.event_queue.get_nowait()
                    
                    # 处理事件
                    self._handle_event_internal(event_data)
                    
                    processed_count += 1
                    self.event_stats["events_processed"] += 1
                    
                except queue.Empty:
                    break
                except Exception as e:
                    print(f"✗ 事件队列处理失败: {e}")
                    self.event_stats["handler_errors"] += 1
                    
            self.event_state["pending_events"] = self.event_queue.qsize()
            
        except Exception as e:
            print(f"✗ 事件队列处理失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def _handle_event_internal(self, event_data: Dict[str, Any]):
        """
        内部事件处理
        
        Args:
            event_data: 事件数据
        """
        try:
            event_type = event_data.get("type")
            event_payload = event_data.get("payload", {})
            event_priority = event_data.get("priority", 0)
            event_timestamp = event_data.get("timestamp", time.time())
            
            # 应用事件过滤器
            if self.event_config["enable_event_filtering"]:
                if not self._apply_event_filters(event_type, event_payload):
                    # 事件被过滤掉
                    return
                    
            # 查找事件处理器
            if event_type in self.event_handlers:
                handlers = self.event_handlers[event_type]
                
                # 按优先级排序处理器
                if self.event_config["enable_event_prioritization"]:
                    handlers = sorted(handlers, key=lambda x: x.get("priority", 0), reverse=True)
                    
                # 调用所有处理器
                for handler_info in handlers:
                    try:
                        handler_func = handler_info["function"]
                        handler_result = handler_func(event_payload)
                        
                        # 检查是否需要停止传播
                        if handler_result is False:
                            break
                            
                    except Exception as e:
                        print(f"✗ 事件处理器执行失败: {event_type} - {e}")
                        self.event_stats["handler_errors"] += 1
                        
            # 触发事件处理回调
            self._trigger_event_callback("event_processed", {
                "event_type": event_type,
                "event_payload": event_payload,
                "processing_time": time.time() - event_timestamp,
                "timestamp": time.time()
            })
            
        except Exception as e:
            print(f"✗ 内部事件处理失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def _apply_event_filters(self, event_type: str, event_payload: Dict[str, Any]) -> bool:
        """
        应用事件过滤器
        
        Args:
            event_type: 事件类型
            event_payload: 事件载荷
            
        Returns:
            是否通过过滤器
        """
        try:
            if event_type in self.event_filters:
                filters = self.event_filters[event_type]
                for filter_func in filters:
                    if not filter_func(event_payload):
                        return False
                        
            return True
            
        except Exception as e:
            print(f"✗ 事件过滤器应用失败: {e}")
            self.event_stats["handler_errors"] += 1
            return True
            
    def emit_event(self, event_type: str, event_payload: Dict[str, Any] = None, 
                   priority: int = 0, async_process: bool = None) -> bool:
        """
        发出事件
        
        Args:
            event_type: 事件类型
            event_payload: 事件载荷
            priority: 事件优先级
            async_process: 是否异步处理
            
        Returns:
            是否发出成功
        """
        try:
            if not self.enabled or not self.event_config["enable_event_system"]:
                return False
                
            # 使用默认异步处理设置或指定设置
            if async_process is None:
                async_process = self.event_config["enable_async_processing"]
                
            event_data = {
                "type": event_type,
                "payload": event_payload or {},
                "priority": priority,
                "timestamp": time.time(),
                "async": async_process
            }
            
            # 触发事件接收回调
            self._trigger_event_callback("event_received", {
                "event_type": event_type,
                "event_payload": event_payload,
                "priority": priority,
                "timestamp": time.time()
            })
            
            # 更新统计
            self.event_stats["events_received"] += 1
            
            if async_process:
                # 异步处理：添加到队列
                try:
                    self.event_queue.put_nowait(event_data)
                    self.event_stats["async_events"] += 1
                    return True
                except queue.Full:
                    # 队列已满，丢弃事件
                    self.event_stats["events_dropped"] += 1
                    self.event_state["dropped_events"] += 1
                    
                    # 触发事件丢弃回调
                    self._trigger_event_callback("event_dropped", {
                        "event_type": event_type,
                        "event_payload": event_payload,
                        "reason": "queue_full",
                        "timestamp": time.time()
                    })
                    
                    return False
            else:
                # 同步处理：立即处理
                self._handle_event_internal(event_data)
                return True
                
        except Exception as e:
            print(f"✗ 事件发出失败: {e}")
            self.event_stats["handler_errors"] += 1
            return False
            
    def register_event_handler(self, event_type: str, handler: Callable, priority: int = 0):
        """
        注册事件处理器
        
        Args:
            event_type: 事件类型
            handler: 处理器函数
            priority: 处理器优先级
        """
        try:
            if event_type not in self.event_handlers:
                self.event_handlers[event_type] = []
                
            handler_info = {
                "function": handler,
                "priority": priority
            }
            
            self.event_handlers[event_type].append(handler_info)
            print(f"✓ 事件处理器已注册: {event_type} (优先级: {priority})")
            
        except Exception as e:
            print(f"✗ 事件处理器注册失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def unregister_event_handler(self, event_type: str, handler: Callable):
        """
        注销事件处理器
        
        Args:
            event_type: 事件类型
            handler: 处理器函数
        """
        try:
            if event_type in self.event_handlers:
                handlers = self.event_handlers[event_type]
                for i, handler_info in enumerate(handlers):
                    if handler_info["function"] == handler:
                        del handlers[i]
                        print(f"✓ 事件处理器已注销: {event_type}")
                        return
                        
            print(f"✗ 事件处理器不存在: {event_type}")
            
        except Exception as e:
            print(f"✗ 事件处理器注销失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def register_event_filter(self, event_type: str, filter_func: Callable):
        """
        注册事件过滤器
        
        Args:
            event_type: 事件类型
            filter_func: 过滤器函数
        """
        try:
            if event_type not in self.event_filters:
                self.event_filters[event_type] = []
                
            self.event_filters[event_type].append(filter_func)
            print(f"✓ 事件过滤器已注册: {event_type}")
            
        except Exception as e:
            print(f"✗ 事件过滤器注册失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def unregister_event_filter(self, event_type: str, filter_func: Callable):
        """
        注销事件过滤器
        
        Args:
            event_type: 事件类型
            filter_func: 过滤器函数
        """
        try:
            if event_type in self.event_filters:
                filters = self.event_filters[event_type]
                if filter_func in filters:
                    filters.remove(filter_func)
                    print(f"✓ 事件过滤器已注销: {event_type}")
                    return
                    
            print(f"✗ 事件过滤器不存在: {event_type}")
            
        except Exception as e:
            print(f"✗ 事件过滤器注销失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    # 默认事件处理器
    def _handle_client_connected(self, payload: Dict[str, Any]):
        """处理客户端连接事件"""
        try:
            client_id = payload.get("client_id")
            connection_data = payload.get("connection_data")
            
            # 添加客户端到客户端管理器
            if self.plugin.client_manager:
                self.plugin.client_manager.add_client(client_id, {
                    "connection_data": connection_data,
                    "ip_address": connection_data.get("remote_address", "") if connection_data else ""
                })
                
        except Exception as e:
            print(f"✗ 客户端连接事件处理失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def _handle_client_disconnected(self, payload: Dict[str, Any]):
        """处理客户端断开连接事件"""
        try:
            client_id = payload.get("client_id")
            reason = payload.get("reason", "unknown")
            
            # 从客户端管理器移除客户端
            if self.plugin.client_manager:
                self.plugin.client_manager.remove_client(client_id, reason)
                
        except Exception as e:
            print(f"✗ 客户端断开连接事件处理失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def _handle_message_received(self, payload: Dict[str, Any]):
        """处理消息接收事件"""
        try:
            client_id = payload.get("client_id")
            message = payload.get("message")
            
            # 将消息传递给消息路由器
            if self.plugin.message_router:
                self.plugin.message_router.route_message(client_id, message)
                
        except Exception as e:
            print(f"✗ 消息接收事件处理失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def _handle_room_created(self, payload: Dict[str, Any]):
        """处理房间创建事件"""
        try:
            room_id = payload.get("room_id")
            room_name = payload.get("room_name")
            
            # 可以在这里添加额外的房间创建逻辑
            print(f"房间已创建: {room_name} ({room_id})")
            
        except Exception as e:
            print(f"✗ 房间创建事件处理失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def _handle_room_destroyed(self, payload: Dict[str, Any]):
        """处理房间销毁事件"""
        try:
            room_id = payload.get("room_id")
            room_name = payload.get("room_name")
            
            # 可以在这里添加额外的房间销毁逻辑
            print(f"房间已销毁: {room_name} ({room_id})")
            
        except Exception as e:
            print(f"✗ 房间销毁事件处理失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def _handle_client_joined_room(self, payload: Dict[str, Any]):
        """处理客户端加入房间事件"""
        try:
            room_id = payload.get("room_id")
            client_id = payload.get("client_id")
            
            # 可以在这里添加额外的客户端加入房间逻辑
            print(f"客户端 {client_id} 已加入房间 {room_id}")
            
        except Exception as e:
            print(f"✗ 客户端加入房间事件处理失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def _handle_client_left_room(self, payload: Dict[str, Any]):
        """处理客户端离开房间事件"""
        try:
            room_id = payload.get("room_id")
            client_id = payload.get("client_id")
            
            # 可以在这里添加额外的客户端离开房间逻辑
            print(f"客户端 {client_id} 已离开房间 {room_id}")
            
        except Exception as e:
            print(f"✗ 客户端离开房间事件处理失败: {e}")
            self.event_stats["handler_errors"] += 1
            
    def get_event_stats(self) -> Dict[str, Any]:
        """
        获取事件统计信息
        
        Returns:
            事件统计字典
        """
        return {
            "state": self.event_state.copy(),
            "stats": self.event_stats.copy(),
            "config": self.event_config.copy(),
            "pending_events": self.event_queue.qsize()
        }
        
    def reset_stats(self):
        """重置事件统计信息"""
        try:
            self.event_stats = {
                "events_received": 0,
                "events_processed": 0,
                "events_dropped": 0,
                "handler_errors": 0,
                "async_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"✗ 事件回调执行失败: {callback_type} - {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}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 事件回调注销失败: {e}")