"""
实时通信插件主文件
为EG引擎提供实时通信功能
"""

import time
from typing import Dict, Any

# 导入各个模块
from .core.websocket_server import WebSocketServer
from .clients.client_manager import ClientManager
from .messaging.message_router import MessageRouter
from .rooms.room_manager import RoomManager
from .protocol.protocol_handler import ProtocolHandler
from .auth.auth_manager import AuthManager
from .serialization.data_serializer import DataSerializer
from .monitoring.communication_monitor import CommunicationMonitor
from .config.comm_config import CommConfig
from .events.event_handler import EventHandler
from .editor.comm_editor import CommEditor

class RealtimeCommunicationPlugin:
    """
    实时通信插件主类
    整合所有通信功能模块
    """
    
    def __init__(self, engine):
        """
        初始化实时通信插件
        
        Args:
            engine: EG引擎实例
        """
        self.engine = engine
        self.enabled = False
        self.initialized = False
        
        # 插件信息
        self.plugin_info = {
            "name": "Realtime Communication Plugin",
            "version": "1.0.0",
            "author": "EG Plugin System",
            "description": "为EG引擎提供实时通信功能"
        }
        
        # 插件状态
        self.plugin_state = {
            "initialized_modules": [],
            "last_update": 0.0,
            "total_messages": 0,
            "active_connections": 0
        }
        
        # 插件统计
        self.plugin_stats = {
            "messages_sent": 0,
            "messages_received": 0,
            "connections_accepted": 0,
            "connections_dropped": 0,
            "errors": 0
        }
        
        # 功能模块
        self.websocket_server = None
        self.client_manager = None
        self.message_router = None
        self.room_manager = None
        self.protocol_handler = None
        self.auth_manager = None
        self.data_serializer = None
        self.monitor = None
        self.config_manager = None
        self.event_handler = None
        self.editor = None
        
        print("✓ 实时通信插件已创建")
        
    def initialize(self) -> bool:
        """
        初始化插件
        
        Returns:
            是否初始化成功
        """
        try:
            print("正在初始化实时通信插件...")
            
            # 初始化配置管理器
            self.config_manager = CommConfig(self)
            if self.config_manager.initialize():
                self.plugin_state["initialized_modules"].append("config_manager")
            else:
                print("✗ 配置管理器初始化失败")
                return False
                
            # 初始化认证管理器
            self.auth_manager = AuthManager(self)
            if self.auth_manager.initialize():
                self.plugin_state["initialized_modules"].append("auth_manager")
            else:
                print("✗ 认证管理器初始化失败")
                return False
                
            # 初始化数据序列化器
            self.data_serializer = DataSerializer(self)
            if self.data_serializer.initialize():
                self.plugin_state["initialized_modules"].append("data_serializer")
            else:
                print("✗ 数据序列化器初始化失败")
                return False
                
            # 初始化协议处理器
            self.protocol_handler = ProtocolHandler(self)
            if self.protocol_handler.initialize():
                self.plugin_state["initialized_modules"].append("protocol_handler")
            else:
                print("✗ 协议处理器初始化失败")
                return False
                
            # 初始化客户端管理器
            self.client_manager = ClientManager(self)
            if self.client_manager.initialize():
                self.plugin_state["initialized_modules"].append("client_manager")
            else:
                print("✗ 客户端管理器初始化失败")
                return False
                
            # 初始化消息路由器
            self.message_router = MessageRouter(self)
            if self.message_router.initialize():
                self.plugin_state["initialized_modules"].append("message_router")
            else:
                print("✗ 消息路由器初始化失败")
                return False
                
            # 初始化房间管理器
            self.room_manager = RoomManager(self)
            if self.room_manager.initialize():
                self.plugin_state["initialized_modules"].append("room_manager")
            else:
                print("✗ 房间管理器初始化失败")
                return False
                
            # 初始化WebSocket服务器
            self.websocket_server = WebSocketServer(self)
            if self.websocket_server.initialize():
                self.plugin_state["initialized_modules"].append("websocket_server")
            else:
                print("✗ WebSocket服务器初始化失败")
                return False
                
            # 初始化事件处理器
            self.event_handler = EventHandler(self)
            if self.event_handler.initialize():
                self.plugin_state["initialized_modules"].append("event_handler")
            else:
                print("✗ 事件处理器初始化失败")
                return False
                
            # 初始化监控系统
            self.monitor = CommunicationMonitor(self)
            if self.monitor.initialize():
                self.plugin_state["initialized_modules"].append("monitor")
            else:
                print("✗ 监控系统初始化失败")
                return False
                
            # 初始化编辑器接口
            self.editor = CommEditor(self)
            if self.editor.initialize():
                self.plugin_state["initialized_modules"].append("editor")
            else:
                print("✗ 编辑器接口初始化失败")
                return False
                
            self.initialized = True
            print("✓ 实时通信插件初始化完成")
            return True
            
        except Exception as e:
            print(f"✗ 实时通信插件初始化失败: {e}")
            self.plugin_stats["errors"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def enable(self) -> bool:
        """
        启用插件
        
        Returns:
            是否启用成功
        """
        try:
            if not self.initialized:
                print("✗ 实时通信插件未初始化")
                return False
                
            print("正在启用实时通信插件...")
            
            # 启用各模块（按依赖顺序）
            modules_to_enable = [
                ("config_manager", self.config_manager),
                ("auth_manager", self.auth_manager),
                ("data_serializer", self.data_serializer),
                ("protocol_handler", self.protocol_handler),
                ("client_manager", self.client_manager),
                ("message_router", self.message_router),
                ("room_manager", self.room_manager),
                ("event_handler", self.event_handler),
                ("monitor", self.monitor),
                ("editor", self.editor),
                ("websocket_server", self.websocket_server)
            ]
            
            for module_name, module in modules_to_enable:
                if module and not module.enable():
                    print(f"✗ {module_name} 启用失败")
                    return False
                elif module:
                    print(f"✓ {module_name} 已启用")
                    
            self.enabled = True
            print("✓ 实时通信插件已启用")
            return True
            
        except Exception as e:
            print(f"✗ 实时通信插件启用失败: {e}")
            self.plugin_stats["errors"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def disable(self):
        """禁用插件"""
        try:
            print("正在禁用实时通信插件...")
            
            # 禁用各模块（按依赖顺序倒序）
            modules_to_disable = [
                ("websocket_server", self.websocket_server),
                ("editor", self.editor),
                ("monitor", self.monitor),
                ("event_handler", self.event_handler),
                ("room_manager", self.room_manager),
                ("message_router", self.message_router),
                ("client_manager", self.client_manager),
                ("protocol_handler", self.protocol_handler),
                ("data_serializer", self.data_serializer),
                ("auth_manager", self.auth_manager),
                ("config_manager", self.config_manager)
            ]
            
            for module_name, module in modules_to_disable:
                if module:
                    module.disable()
                    print(f"✓ {module_name} 已禁用")
                    
            self.enabled = False
            print("✓ 实时通信插件已禁用")
            
        except Exception as e:
            print(f"✗ 实时通信插件禁用失败: {e}")
            self.plugin_stats["errors"] += 1
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理插件资源"""
        try:
            print("正在清理实时通信插件资源...")
            
            # 禁用插件
            if self.enabled:
                self.disable()
                
            # 清理各模块
            modules_to_finalize = [
                self.websocket_server,
                self.client_manager,
                self.message_router,
                self.room_manager,
                self.protocol_handler,
                self.auth_manager,
                self.data_serializer,
                self.monitor,
                self.config_manager,
                self.event_handler,
                self.editor
            ]
            
            for module in modules_to_finalize:
                if module:
                    module.finalize()
                    
            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()
            
            # 更新各模块
            if self.websocket_server:
                self.websocket_server.update(dt)
                
            if self.client_manager:
                self.client_manager.update(dt)
                
            if self.message_router:
                self.message_router.update(dt)
                
            if self.room_manager:
                self.room_manager.update(dt)
                
            if self.monitor:
                self.monitor.update(dt)
                
            if self.editor:
                self.editor.update(dt)
                
            self.plugin_state["last_update"] = current_time
            
        except Exception as e:
            print(f"✗ 实时通信插件更新失败: {e}")
            self.plugin_stats["errors"] += 1
            import traceback
            traceback.print_exc()
            
    def get_plugin_info(self) -> Dict[str, Any]:
        """
        获取插件信息
        
        Returns:
            插件信息字典
        """
        return self.plugin_info.copy()
        
    def get_plugin_state(self) -> Dict[str, Any]:
        """
        获取插件状态
        
        Returns:
            插件状态字典
        """
        return self.plugin_state.copy()
        
    def get_plugin_stats(self) -> Dict[str, Any]:
        """
        获取插件统计信息
        
        Returns:
            插件统计字典
        """
        return {
            "info": self.plugin_info.copy(),
            "state": self.plugin_state.copy(),
            "stats": self.plugin_stats.copy()
        }
        
    def reset_stats(self):
        """重置插件统计信息"""
        try:
            self.plugin_stats = {
                "messages_sent": 0,
                "messages_received": 0,
                "connections_accepted": 0,
                "connections_dropped": 0,
                "errors": 0
            }
            print("✓ 插件统计信息已重置")
        except Exception as e:
            print(f"✗ 插件统计信息重置失败: {e}")

# 插件导出
plugin = RealtimeCommunicationPlugin