"""
服务器架构插件
为EG引擎提供完整的服务器架构支持
"""

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

class ServerArchitecturePlugin:
    """
    服务器架构插件主类
    整合所有服务器功能模块
    """
    
    def __init__(self, engine):
        """
        初始化服务器架构插件
        
        Args:
            engine: EG引擎实例
        """
        self.engine = engine
        self.enabled = False
        self.initialized = False
        
        # 插件元数据
        self.plugin_info = {
            "name": "Server Architecture Plugin",
            "version": "1.0.0",
            "author": "EG Development Team",
            "description": "为EG引擎提供完整的服务器架构支持"
        }
        
        # 核心模块
        self.server_manager = None
        self.client_manager = None
        self.message_router = None
        self.room_manager = None
        self.storage_manager = None
        self.load_balancer = None
        self.monitoring_system = None
        self.config_manager = None
        self.security_manager = None
        self.api_interface = None
        self.editor_interface = None
        
        # 插件状态
        self.plugin_state = {
            "startup_time": 0.0,
            "last_update": 0.0,
            "total_clients": 0,
            "total_rooms": 0,
            "messages_processed": 0,
            "bytes_transferred": 0
        }
        
        # 插件配置
        self.plugin_config = {
            "enable_monitoring": True,
            "enable_logging": True,
            "max_clients": 1000,
            "server_port": 8080,
            "enable_ssl": False,
            "log_level": "INFO"
        }
        
        # 统计信息
        self.stats = {
            "initialization_count": 0,
            "enable_count": 0,
            "disable_count": 0,
            "error_count": 0
        }
        
        # 回调函数
        self.callbacks = {
            "plugin_initialized": [],
            "plugin_enabled": [],
            "plugin_disabled": [],
            "error_occurred": []
        }
        
        print("✓ 服务器架构插件已创建")
        
    def initialize(self) -> bool:
        """
        初始化插件
        
        Returns:
            是否初始化成功
        """
        try:
            print("正在初始化服务器架构插件...")
            
            # 初始化各个模块
            self._initialize_modules()
            
            self.initialized = True
            self.stats["initialization_count"] += 1
            self.plugin_state["startup_time"] = time.time()
            
            # 触发初始化完成回调
            self._trigger_callback("plugin_initialized", {
                "timestamp": self.plugin_state["startup_time"]
            })
            
            print("✓ 服务器架构插件初始化完成")
            return True
            
        except Exception as e:
            print(f"✗ 服务器架构插件初始化失败: {e}")
            self.stats["error_count"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def _initialize_modules(self):
        """初始化各个功能模块"""
        try:
            # 初始化配置管理器
            from .config.config_manager import ConfigManager
            self.config_manager = ConfigManager(self)
            self.config_manager.initialize()
            
            # 初始化安全管理系统
            from .security.security_manager import SecurityManager
            self.security_manager = SecurityManager(self)
            self.security_manager.initialize()
            
            # 初始化存储管理器
            from .storage.storage_manager import StorageManager
            self.storage_manager = StorageManager(self)
            self.storage_manager.initialize()
            
            # 初始化客户端管理器
            from .clients.client_manager import ClientManager
            self.client_manager = ClientManager(self)
            self.client_manager.initialize()
            
            # 初始化消息路由系统
            from .messaging.message_router import MessageRouter
            self.message_router = MessageRouter(self)
            self.message_router.initialize()
            
            # 初始化房间管理器
            from .rooms.room_manager import RoomManager
            self.room_manager = RoomManager(self)
            self.room_manager.initialize()
            
            # 初始化服务器管理器
            from .core.server_manager import ServerManager
            self.server_manager = ServerManager(self)
            self.server_manager.initialize()
            
            # 初始化负载均衡器
            from .loadbalancer.load_balancer import LoadBalancer
            self.load_balancer = LoadBalancer(self)
            self.load_balancer.initialize()
            
            # 初始化监控系统
            if self.plugin_config["enable_monitoring"]:
                from .monitoring.monitoring_system import MonitoringSystem
                self.monitoring_system = MonitoringSystem(self)
                self.monitoring_system.initialize()
                
            # 初始化API接口
            from .api.api_interface import APIInterface
            self.api_interface = APIInterface(self)
            self.api_interface.initialize()
            
            # 初始化编辑器接口
            from .editor.editor_interface import EditorInterface
            self.editor_interface = EditorInterface(self)
            self.editor_interface.initialize()
            
            print("✓ 所有模块初始化完成")
            
        except Exception as e:
            print(f"✗ 模块初始化失败: {e}")
            raise
            
    def enable(self) -> bool:
        """
        启用插件
        
        Returns:
            是否启用成功
        """
        try:
            if not self.initialized:
                print("✗ 插件未初始化")
                return False
                
            print("正在启用服务器架构插件...")
            
            # 启用各个模块
            self._enable_modules()
            
            self.enabled = True
            self.stats["enable_count"] += 1
            
            # 触发启用完成回调
            self._trigger_callback("plugin_enabled", {
                "timestamp": time.time()
            })
            
            print("✓ 服务器架构插件已启用")
            return True
            
        except Exception as e:
            print(f"✗ 服务器架构插件启用失败: {e}")
            self.stats["error_count"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def _enable_modules(self):
        """启用各个功能模块"""
        try:
            # 按依赖顺序启用模块
            if self.config_manager:
                self.config_manager.enable()
                
            if self.security_manager:
                self.security_manager.enable()
                
            if self.storage_manager:
                self.storage_manager.enable()
                
            if self.client_manager:
                self.client_manager.enable()
                
            if self.message_router:
                self.message_router.enable()
                
            if self.room_manager:
                self.room_manager.enable()
                
            if self.load_balancer:
                self.load_balancer.enable()
                
            if self.monitoring_system:
                self.monitoring_system.enable()
                
            if self.api_interface:
                self.api_interface.enable()
                
            if self.editor_interface:
                self.editor_interface.enable()
                
            # 最后启用服务器管理器
            if self.server_manager:
                self.server_manager.enable()
                
            print("✓ 所有模块已启用")
            
        except Exception as e:
            print(f"✗ 模块启用失败: {e}")
            raise
            
    def disable(self):
        """禁用插件"""
        try:
            if not self.enabled:
                return
                
            print("正在禁用服务器架构插件...")
            
            # 禁用各个模块
            self._disable_modules()
            
            self.enabled = False
            self.stats["disable_count"] += 1
            
            # 触发禁用完成回调
            self._trigger_callback("plugin_disabled", {
                "timestamp": time.time()
            })
            
            print("✓ 服务器架构插件已禁用")
            
        except Exception as e:
            print(f"✗ 服务器架构插件禁用失败: {e}")
            self.stats["error_count"] += 1
            import traceback
            traceback.print_exc()
            
    def _disable_modules(self):
        """禁用各个功能模块"""
        try:
            # 按依赖顺序禁用模块（与启用顺序相反）
            if self.server_manager:
                self.server_manager.disable()
                
            if self.editor_interface:
                self.editor_interface.disable()
                
            if self.api_interface:
                self.api_interface.disable()
                
            if self.monitoring_system:
                self.monitoring_system.disable()
                
            if self.load_balancer:
                self.load_balancer.disable()
                
            if self.room_manager:
                self.room_manager.disable()
                
            if self.message_router:
                self.message_router.disable()
                
            if self.client_manager:
                self.client_manager.disable()
                
            if self.storage_manager:
                self.storage_manager.disable()
                
            if self.security_manager:
                self.security_manager.disable()
                
            if self.config_manager:
                self.config_manager.disable()
                
            print("✓ 所有模块已禁用")
            
        except Exception as e:
            print(f"✗ 模块禁用失败: {e}")
            raise
            
    def finalize(self):
        """清理插件资源"""
        try:
            print("正在清理服务器架构插件资源...")
            
            # 禁用插件
            if self.enabled:
                self.disable()
                
            # 清理各个模块
            self._finalize_modules()
            
            # 清理回调
            self.callbacks.clear()
            
            self.initialized = False
            print("✓ 服务器架构插件资源已清理")
            
        except Exception as e:
            print(f"✗ 服务器架构插件资源清理失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _finalize_modules(self):
        """清理各个功能模块"""
        try:
            # 按依赖顺序清理模块（与启用顺序相反）
            modules = [
                self.server_manager,
                self.editor_interface,
                self.api_interface,
                self.monitoring_system,
                self.load_balancer,
                self.room_manager,
                self.message_router,
                self.client_manager,
                self.storage_manager,
                self.security_manager,
                self.config_manager
            ]
            
            for module in modules:
                if module and hasattr(module, 'finalize'):
                    try:
                        module.finalize()
                    except Exception as e:
                        print(f"✗ 模块清理失败: {module.__class__.__name__} - {e}")
                        
        except Exception as e:
            print(f"✗ 模块资源清理失败: {e}")
            
    def update(self, dt: float):
        """
        更新插件状态
        
        Args:
            dt: 时间增量（秒）
        """
        try:
            if not self.enabled:
                return
                
            current_time = time.time()
            self.plugin_state["last_update"] = current_time
            
            # 更新各个模块
            self._update_modules(dt)
            
        except Exception as e:
            print(f"✗ 服务器架构插件更新失败: {e}")
            self.stats["error_count"] += 1
            import traceback
            traceback.print_exc()
            
    def _update_modules(self, dt: float):
        """更新各个功能模块"""
        try:
            # 更新顺序考虑依赖关系
            if self.monitoring_system:
                self.monitoring_system.update(dt)
                
            if self.server_manager:
                self.server_manager.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.load_balancer:
                self.load_balancer.update(dt)
                
            if self.storage_manager:
                self.storage_manager.update(dt)
                
            if self.security_manager:
                self.security_manager.update(dt)
                
            if self.api_interface:
                self.api_interface.update(dt)
                
            if self.editor_interface:
                self.editor_interface.update(dt)
                
        except Exception as e:
            print(f"✗ 模块更新失败: {e}")
            raise
            
    def get_stats(self) -> Dict[str, Any]:
        """
        获取插件统计信息
        
        Returns:
            统计信息字典
        """
        try:
            # 收集各模块统计信息
            module_stats = {}
            
            if self.server_manager:
                module_stats["server"] = self.server_manager.get_server_stats()
                
            if self.client_manager:
                module_stats["clients"] = self.client_manager.get_client_stats()
                
            if self.message_router:
                module_stats["messages"] = self.message_router.get_message_stats()
                
            if self.room_manager:
                module_stats["rooms"] = self.room_manager.get_room_stats()
                
            if self.storage_manager:
                module_stats["storage"] = self.storage_manager.get_storage_stats()
                
            if self.monitoring_system:
                module_stats["monitoring"] = self.monitoring_system.get_monitoring_stats()
                
            # 合并插件统计
            stats = {
                "plugin": self.stats,
                "state": self.plugin_state,
                "modules": module_stats
            }
            
            return stats
            
        except Exception as e:
            print(f"✗ 统计信息获取失败: {e}")
            return {}
            
    def reset_stats(self):
        """重置统计信息"""
        try:
            self.stats = {
                "initialization_count": 0,
                "enable_count": 0,
                "disable_count": 0,
                "error_count": 0
            }
            
            # 重置各模块统计
            modules = [
                self.server_manager,
                self.client_manager,
                self.message_router,
                self.room_manager,
                self.storage_manager,
                self.monitoring_system
            ]
            
            for module in modules:
                if module and hasattr(module, 'reset_stats'):
                    module.reset_stats()
                    
            print("✓ 统计信息已重置")
            
        except Exception as e:
            print(f"✗ 统计信息重置失败: {e}")
            
    def _trigger_callback(self, callback_type: str, data: Dict[str, Any]):
        """
        触发回调函数
        
        Args:
            callback_type: 回调类型
            data: 回调数据
        """
        try:
            if callback_type in self.callbacks:
                for callback in self.callbacks[callback_type]:
                    try:
                        callback(data)
                    except Exception as e:
                        print(f"✗ 回调执行失败: {callback_type} - {e}")
        except Exception as e:
            print(f"✗ 回调触发失败: {e}")
            
    def register_callback(self, callback_type: str, callback: callable):
        """
        注册回调函数
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.callbacks:
                self.callbacks[callback_type].append(callback)
                print(f"✓ 回调已注册: {callback_type}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 回调注册失败: {e}")
            
    def unregister_callback(self, callback_type: str, callback: callable):
        """
        注销回调函数
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.callbacks:
                if callback in self.callbacks[callback_type]:
                    self.callbacks[callback_type].remove(callback)
                    print(f"✓ 回调已注销: {callback_type}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 回调注销失败: {e}")
            
    def get_info(self) -> Dict[str, Any]:
        """
        获取插件信息
        
        Returns:
            插件信息字典
        """
        return self.plugin_info.copy()
        
    def get_config(self) -> Dict[str, Any]:
        """
        获取插件配置
        
        Returns:
            插件配置字典
        """
        return self.plugin_config.copy()
        
    def set_config(self, config: Dict[str, Any]) -> bool:
        """
        设置插件配置
        
        Args:
            config: 配置字典
            
        Returns:
            是否设置成功
        """
        try:
            self.plugin_config.update(config)
            print(f"✓ 插件配置已更新: {self.plugin_config}")
            return True
        except Exception as e:
            print(f"✗ 插件配置设置失败: {e}")
            return False