"""
服务器管理器模块
负责服务器的启动、停止和状态管理
"""

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

class ServerManager:
    """
    服务器管理器
    负责服务器的启动、停止和状态管理
    """
    
    def __init__(self, plugin):
        """
        初始化服务器管理器
        
        Args:
            plugin: 服务器架构插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        self.running = False
        
        # 服务器配置
        self.server_config = {
            "host": "0.0.0.0",
            "port": 8080,
            "max_connections": 1000,
            "enable_ssl": False,
            "ssl_cert_file": "",
            "ssl_key_file": "",
            "connection_timeout": 30.0,
            "heartbeat_interval": 5.0,
            "enable_compression": True,
            "max_message_size": 65536
        }
        
        # 服务器状态
        self.server_state = {
            "is_running": False,
            "start_time": 0.0,
            "uptime": 0.0,
            "current_connections": 0,
            "total_connections": 0,
            "peak_connections": 0,
            "bytes_sent": 0,
            "bytes_received": 0,
            "packets_sent": 0,
            "packets_received": 0
        }
        
        # 服务器统计
        self.server_stats = {
            "servers_started": 0,
            "servers_stopped": 0,
            "connection_attempts": 0,
            "successful_connections": 0,
            "failed_connections": 0,
            "disconnections": 0,
            "timeouts": 0,
            "errors": 0
        }
        
        # 服务器套接字
        self.server_socket = None
        self.ssl_context = None
        
        # 线程管理
        self.server_thread = None
        self.heartbeat_thread = None
        self.client_threads = []
        
        # 回调函数
        self.server_callbacks = {
            "server_started": [],
            "server_stopped": [],
            "client_connected": [],
            "client_disconnected": [],
            "error_occurred": []
        }
        
        # 时间戳记录
        self.last_heartbeat = 0.0
        self.last_update = 0.0
        
        print("✓ 服务器管理器已创建")
        
    def initialize(self) -> bool:
        """
        初始化服务器管理器
        
        Returns:
            是否初始化成功
        """
        try:
            print("正在初始化服务器管理器...")
            
            # 初始化SSL上下文（如果启用）
            if self.server_config["enable_ssl"]:
                self._initialize_ssl()
                
            self.initialized = True
            print("✓ 服务器管理器初始化完成")
            return True
            
        except Exception as e:
            print(f"✗ 服务器管理器初始化失败: {e}")
            self.server_stats["errors"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def _initialize_ssl(self):
        """初始化SSL上下文"""
        try:
            import ssl
            
            self.ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            if self.server_config["ssl_cert_file"] and self.server_config["ssl_key_file"]:
                self.ssl_context.load_cert_chain(
                    self.server_config["ssl_cert_file"],
                    self.server_config["ssl_key_file"]
                )
            print("✓ SSL上下文已初始化")
        except Exception as e:
            print(f"✗ SSL初始化失败: {e}")
            self.server_config["enable_ssl"] = False
            
    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.server_stats["errors"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def disable(self):
        """禁用服务器管理器"""
        try:
            self.enabled = False
            
            # 停止服务器
            if self.server_state["is_running"]:
                self.stop_server()
                
            print("✓ 服务器管理器已禁用")
            
        except Exception as e:
            print(f"✗ 服务器管理器禁用失败: {e}")
            self.server_stats["errors"] += 1
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理服务器管理器资源"""
        try:
            # 禁用管理器
            if self.enabled:
                self.disable()
                
            # 清理回调
            self.server_callbacks.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.last_update = current_time
            
            # 更新服务器运行时间
            if self.server_state["is_running"]:
                self.server_state["uptime"] = current_time - self.server_state["start_time"]
                
        except Exception as e:
            print(f"✗ 服务器管理器更新失败: {e}")
            self.server_stats["errors"] += 1
            import traceback
            traceback.print_exc()
            
    def start_server(self, host: str = None, port: int = None) -> bool:
        """
        启动服务器
        
        Args:
            host: 服务器主机地址
            port: 服务器端口
            
        Returns:
            是否启动成功
        """
        try:
            if not self.enabled:
                print("✗ 服务器管理器未启用")
                return False
                
            if self.server_state["is_running"]:
                print("✗ 服务器已在运行")
                return False
                
            # 使用配置的默认值或传入的参数
            if host is None:
                host = self.server_config["host"]
            if port is None:
                port = self.server_config["port"]
                
            # 创建服务器套接字
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            
            # 绑定地址和端口
            self.server_socket.bind((host, port))
            self.server_socket.listen(self.server_config["max_connections"])
            
            # 如果启用SSL，包装套接字
            if self.server_config["enable_ssl"] and self.ssl_context:
                self.server_socket = self.ssl_context.wrap_socket(
                    self.server_socket, 
                    server_side=True
                )
                
            self.running = True
            self.server_state["is_running"] = True
            self.server_state["start_time"] = time.time()
            
            # 启动服务器线程
            self.server_thread = threading.Thread(target=self._server_loop, daemon=True)
            self.server_thread.start()
            
            # 启动心跳线程
            self.heartbeat_thread = threading.Thread(target=self._heartbeat_loop, daemon=True)
            self.heartbeat_thread.start()
            
            self.server_stats["servers_started"] += 1
            
            # 触发服务器启动回调
            self._trigger_server_callback("server_started", {
                "host": host,
                "port": port,
                "timestamp": self.server_state["start_time"]
            })
            
            print(f"✓ 服务器已启动: {host}:{port}")
            return True
            
        except Exception as e:
            print(f"✗ 服务器启动失败: {e}")
            self.server_stats["errors"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def stop_server(self):
        """停止服务器"""
        try:
            if not self.server_state["is_running"]:
                return
                
            print("正在停止服务器...")
            
            # 停止服务器循环
            self.running = False
            
            # 关闭服务器套接字
            if self.server_socket:
                self.server_socket.close()
                self.server_socket = None
                
            # 等待线程结束
            if self.server_thread and self.server_thread.is_alive():
                self.server_thread.join(timeout=5.0)
                
            if self.heartbeat_thread and self.heartbeat_thread.is_alive():
                self.heartbeat_thread.join(timeout=5.0)
                
            # 清理客户端线程
            for client_thread in self.client_threads:
                if client_thread.is_alive():
                    client_thread.join(timeout=1.0)
            self.client_threads.clear()
            
            # 重置服务器状态
            self.server_state["is_running"] = False
            self.server_state["start_time"] = 0.0
            self.server_state["uptime"] = 0.0
            
            self.server_stats["servers_stopped"] += 1
            
            # 触发服务器停止回调
            self._trigger_server_callback("server_stopped", {
                "timestamp": time.time()
            })
            
            print("✓ 服务器已停止")
            
        except Exception as e:
            print(f"✗ 服务器停止失败: {e}")
            self.server_stats["errors"] += 1
            import traceback
            traceback.print_exc()
            
    def _server_loop(self):
        """服务器主循环"""
        try:
            print("服务器主循环已启动")
            
            while self.running and self.server_socket:
                try:
                    # 接受客户端连接
                    client_socket, client_address = self.server_socket.accept()
                    
                    self.server_stats["connection_attempts"] += 1
                    
                    # 检查连接限制
                    if self.server_state["current_connections"] >= self.server_config["max_connections"]:
                        client_socket.close()
                        self.server_stats["failed_connections"] += 1
                        continue
                        
                    # 处理客户端连接
                    client_thread = threading.Thread(
                        target=self._handle_client,
                        args=(client_socket, client_address),
                        daemon=True
                    )
                    client_thread.start()
                    self.client_threads.append(client_thread)
                    
                    self.server_stats["successful_connections"] += 1
                    self.server_state["current_connections"] += 1
                    self.server_state["total_connections"] += 1
                    if self.server_state["current_connections"] > self.server_state["peak_connections"]:
                        self.server_state["peak_connections"] = self.server_state["current_connections"]
                        
                except socket.error as e:
                    if self.running:  # 只在服务器运行时报告错误
                        print(f"✗ 接受连接时出错: {e}")
                        self.server_stats["errors"] += 1
                except Exception as e:
                    if self.running:
                        print(f"✗ 服务器循环错误: {e}")
                        self.server_stats["errors"] += 1
                        
        except Exception as e:
            print(f"✗ 服务器主循环失败: {e}")
            self.server_stats["errors"] += 1
        finally:
            print("服务器主循环已结束")
            
    def _handle_client(self, client_socket, client_address):
        """
        处理客户端连接
        
        Args:
            client_socket: 客户端套接字
            client_address: 客户端地址
        """
        try:
            print(f"✓ 客户端已连接: {client_address}")
            
            # 触发客户端连接回调
            self._trigger_server_callback("client_connected", {
                "address": client_address,
                "timestamp": time.time()
            })
            
            # 处理客户端消息循环
            self._client_message_loop(client_socket, client_address)
            
        except Exception as e:
            print(f"✗ 客户端处理失败: {client_address} - {e}")
            self.server_stats["errors"] += 1
        finally:
            # 清理客户端连接
            try:
                client_socket.close()
            except:
                pass
                
            self.server_state["current_connections"] -= 1
            self.server_stats["disconnections"] += 1
            
            # 触发客户端断开回调
            self._trigger_server_callback("client_disconnected", {
                "address": client_address,
                "timestamp": time.time()
            })
            
            print(f"✓ 客户端已断开: {client_address}")
            
    def _client_message_loop(self, client_socket, client_address):
        """
        客户端消息循环
        
        Args:
            client_socket: 客户端套接字
            client_address: 客户端地址
        """
        try:
            # 设置超时
            client_socket.settimeout(self.server_config["connection_timeout"])
            
            while self.running:
                try:
                    # 接收消息
                    message = client_socket.recv(self.server_config["max_message_size"])
                    if not message:
                        break
                        
                    self.server_state["bytes_received"] += len(message)
                    self.server_state["packets_received"] += 1
                    
                    # 处理消息
                    self._process_client_message(message, client_socket, client_address)
                    
                except socket.timeout:
                    print(f"✗ 客户端超时: {client_address}")
                    self.server_stats["timeouts"] += 1
                    break
                except socket.error as e:
                    if self.running:
                        print(f"✗ 客户端通信错误: {client_address} - {e}")
                        self.server_stats["errors"] += 1
                    break
                except Exception as e:
                    if self.running:
                        print(f"✗ 客户端消息处理错误: {client_address} - {e}")
                        self.server_stats["errors"] += 1
                    break
                    
        except Exception as e:
            print(f"✗ 客户端消息循环失败: {client_address} - {e}")
            self.server_stats["errors"] += 1
            
    def _process_client_message(self, message: bytes, client_socket, client_address):
        """
        处理客户端消息
        
        Args:
            message: 接收到的消息
            client_socket: 客户端套接字
            client_address: 客户端地址
        """
        try:
            # 将消息传递给消息路由系统处理
            if self.plugin.message_router:
                self.plugin.message_router.route_message(
                    message, 
                    client_address, 
                    client_socket
                )
        except Exception as e:
            print(f"✗ 消息处理失败: {client_address} - {e}")
            self.server_stats["errors"] += 1
            
    def _heartbeat_loop(self):
        """心跳循环"""
        try:
            print("心跳循环已启动")
            
            while self.running:
                try:
                    current_time = time.time()
                    
                    # 发送心跳消息
                    if self.plugin.client_manager:
                        self.plugin.client_manager.send_heartbeat()
                        
                    self.last_heartbeat = current_time
                    
                    # 等待下一个心跳间隔
                    time.sleep(self.server_config["heartbeat_interval"])
                    
                except Exception as e:
                    if self.running:
                        print(f"✗ 心跳循环错误: {e}")
                        self.server_stats["errors"] += 1
                    time.sleep(1.0)  # 出错时短暂休眠
                    
        except Exception as e:
            print(f"✗ 心跳循环失败: {e}")
            self.server_stats["errors"] += 1
        finally:
            print("心跳循环已结束")
            
    def send_message_to_client(self, message: bytes, client_socket) -> bool:
        """
        发送消息到客户端
        
        Args:
            message: 要发送的消息
            client_socket: 客户端套接字
            
        Returns:
            是否发送成功
        """
        try:
            if not self.server_state["is_running"]:
                return False
                
            client_socket.send(message)
            self.server_state["bytes_sent"] += len(message)
            self.server_state["packets_sent"] += 1
            return True
            
        except Exception as e:
            print(f"✗ 消息发送失败: {e}")
            self.server_stats["errors"] += 1
            return False
            
    def get_server_stats(self) -> Dict[str, Any]:
        """
        获取服务器统计信息
        
        Returns:
            服务器统计字典
        """
        return {
            "state": self.server_state.copy(),
            "stats": self.server_stats.copy(),
            "config": self.server_config.copy()
        }
        
    def reset_stats(self):
        """重置服务器统计信息"""
        try:
            self.server_stats = {
                "servers_started": 0,
                "servers_stopped": 0,
                "connection_attempts": 0,
                "successful_connections": 0,
                "failed_connections": 0,
                "disconnections": 0,
                "timeouts": 0,
                "errors": 0
            }
            print("✓ 服务器统计信息已重置")
        except Exception as e:
            print(f"✗ 服务器统计信息重置失败: {e}")
            
    def set_server_config(self, config: Dict[str, Any]) -> bool:
        """
        设置服务器配置
        
        Args:
            config: 服务器配置字典
            
        Returns:
            是否设置成功
        """
        try:
            self.server_config.update(config)
            print(f"✓ 服务器配置已更新: {self.server_config}")
            return True
        except Exception as e:
            print(f"✗ 服务器配置设置失败: {e}")
            return False
            
    def get_server_config(self) -> Dict[str, Any]:
        """
        获取服务器配置
        
        Returns:
            服务器配置字典
        """
        return self.server_config.copy()
        
    def is_server_running(self) -> bool:
        """
        检查服务器是否正在运行
        
        Returns:
            服务器是否正在运行
        """
        return self.server_state["is_running"]
        
    def _trigger_server_callback(self, callback_type: str, data: Dict[str, Any]):
        """
        触发服务器回调
        
        Args:
            callback_type: 回调类型
            data: 回调数据
        """
        try:
            if callback_type in self.server_callbacks:
                for callback in self.server_callbacks[callback_type]:
                    try:
                        callback(data)
                    except Exception as e:
                        print(f"✗ 服务器回调执行失败: {callback_type} - {e}")
        except Exception as e:
            print(f"✗ 服务器回调触发失败: {e}")
            
    def register_server_callback(self, callback_type: str, callback: callable):
        """
        注册服务器回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.server_callbacks:
                self.server_callbacks[callback_type].append(callback)
                print(f"✓ 服务器回调已注册: {callback_type}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 服务器回调注册失败: {e}")
            
    def unregister_server_callback(self, callback_type: str, callback: callable):
        """
        注销服务器回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.server_callbacks:
                if callback in self.server_callbacks[callback_type]:
                    self.server_callbacks[callback_type].remove(callback)
                    print(f"✓ 服务器回调已注销: {callback_type}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 服务器回调注销失败: {e}")