"""
匹配管理器模块
管理匹配过程和规则
"""

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

class MatchManager:
    """
    匹配管理器
    管理匹配过程和规则
    """
    
    def __init__(self, plugin):
        """
        初始化匹配管理器
        
        Args:
            plugin: 匹配系统插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 匹配配置
        self.match_config = {
            "enable_matchmaking": True,
            "matchmaking_interval": 1.0,
            "max_match_attempts": 3,
            "match_timeout": 30.0,
            "enable_skill_based_matching": True,
            "enable_team_balancing": True,
            "enable_cross_platform_matching": True
        }
        
        # 匹配状态
        self.match_state = {
            "is_matching": False,
            "active_matches": 0,
            "successful_matches": 0,
            "failed_matches": 0,
            "last_match_time": 0.0
        }
        
        # 匹配统计
        self.match_stats = {
            "matches_started": 0,
            "matches_completed": 0,
            "matches_cancelled": 0,
            "average_match_time": 0.0,
            "match_errors": 0
        }
        
        # 匹配锁
        self.match_lock = threading.RLock()
        
        # 回调函数
        self.match_callbacks = {
            "match_started": [],
            "match_completed": [],
            "match_cancelled": [],
            "match_error": []
        }
        
        # 时间戳记录
        self.last_matchmaking_run = 0.0
        self.last_stats_reset = 0.0
        
        print("✓ 匹配管理器已创建")
        
    def initialize(self) -> bool:
        """
        初始化匹配管理器
        
        Returns:
            是否初始化成功
        """
        try:
            print("正在初始化匹配管理器...")
            
            self.initialized = True
            print("✓ 匹配管理器初始化完成")
            return True
            
        except Exception as e:
            print(f"✗ 匹配管理器初始化失败: {e}")
            self.match_stats["match_errors"] += 1
            import traceback
            traceback.print_exc()
            return 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.match_stats["match_errors"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def disable(self):
        """禁用匹配管理器"""
        try:
            self.enabled = False
            print("✓ 匹配管理器已禁用")
            
        except Exception as e:
            print(f"✗ 匹配管理器禁用失败: {e}")
            self.match_stats["match_errors"] += 1
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理匹配管理器资源"""
        try:
            # 禁用匹配管理器
            if self.enabled:
                self.disable()
                
            # 清理回调
            self.match_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()
            
            # 定期运行匹配算法
            if current_time - self.last_matchmaking_run >= self.match_config["matchmaking_interval"]:
                self._run_matchmaking()
                self.last_matchmaking_run = current_time
                
            self.match_state["last_match_time"] = current_time
            
        except Exception as e:
            print(f"✗ 匹配管理器更新失败: {e}")
            self.match_stats["match_errors"] += 1
            import traceback
            traceback.print_exc()
            
    def _run_matchmaking(self):
        """运行匹配算法"""
        try:
            if not self.match_config["enable_matchmaking"]:
                return
                
            # 通知队列管理器运行匹配
            if self.plugin.queue_manager:
                self.plugin.queue_manager.process_queues()
                
        except Exception as e:
            print(f"✗ 匹配算法运行失败: {e}")
            self.match_stats["match_errors"] += 1
            
    def start_matchmaking(self, player_ids: List[str], match_params: Dict[str, Any] = None) -> str:
        """
        开始匹配
        
        Args:
            player_ids: 玩家ID列表
            match_params: 匹配参数
            
        Returns:
            匹配ID
        """
        try:
            if not self.enabled:
                raise Exception("匹配管理器未启用")
                
            # 生成匹配ID
            match_id = f"match_{int(time.time() * 1000000)}"
            
            # 添加玩家到队列
            if self.plugin.queue_manager:
                queue_success = self.plugin.queue_manager.add_players_to_queue(
                    player_ids, match_params or {})
                    
                if queue_success:
                    self.match_stats["matches_started"] += 1
                    self.match_state["active_matches"] += 1
                    
                    # 触发匹配开始回调
                    self._trigger_match_callback("match_started", {
                        "match_id": match_id,
                        "player_ids": player_ids,
                        "match_params": match_params,
                        "timestamp": time.time()
                    })
                    
                    print(f"✓ 匹配已开始: {match_id}")
                    return match_id
                else:
                    raise Exception("添加玩家到队列失败")
            else:
                raise Exception("队列管理器不可用")
                
        except Exception as e:
            print(f"✗ 匹配开始失败: {e}")
            self.match_stats["match_errors"] += 1
            
            # 触发匹配错误回调
            self._trigger_match_callback("match_error", {
                "player_ids": player_ids,
                "error": str(e),
                "timestamp": time.time()
            })
            
            return ""
            
    def cancel_matchmaking(self, match_id: str) -> bool:
        """
        取消匹配
        
        Args:
            match_id: 匹配ID
            
        Returns:
            是否取消成功
        """
        try:
            # 从队列中移除玩家
            if self.plugin.queue_manager:
                cancel_success = self.plugin.queue_manager.remove_players_from_queue(match_id)
                
                if cancel_success:
                    self.match_stats["matches_cancelled"] += 1
                    if self.match_state["active_matches"] > 0:
                        self.match_state["active_matches"] -= 1
                        
                    # 触发匹配取消回调
                    self._trigger_match_callback("match_cancelled", {
                        "match_id": match_id,
                        "timestamp": time.time()
                    })
                    
                    print(f"✓ 匹配已取消: {match_id}")
                    return True
                else:
                    return False
            else:
                return False
                
        except Exception as e:
            print(f"✗ 匹配取消失败: {e}")
            self.match_stats["match_errors"] += 1
            return False
            
    def complete_match(self, match_id: str, room_id: str) -> bool:
        """
        完成匹配
        
        Args:
            match_id: 匹配ID
            room_id: 房间ID
            
        Returns:
            是否完成成功
        """
        try:
            self.match_stats["matches_completed"] += 1
            self.match_state["successful_matches"] += 1
            if self.match_state["active_matches"] > 0:
                self.match_state["active_matches"] -= 1
                
            # 触发匹配完成回调
            self._trigger_match_callback("match_completed", {
                "match_id": match_id,
                "room_id": room_id,
                "timestamp": time.time()
            })
            
            print(f"✓ 匹配已完成: {match_id} -> 房间: {room_id}")
            return True
            
        except Exception as e:
            print(f"✗ 匹配完成失败: {e}")
            self.match_stats["match_errors"] += 1
            return False
            
    def get_match_stats(self) -> Dict[str, Any]:
        """
        获取匹配统计信息
        
        Returns:
            匹配统计字典
        """
        return {
            "state": self.match_state.copy(),
            "stats": self.match_stats.copy(),
            "config": self.match_config.copy()
        }
        
    def reset_stats(self):
        """重置匹配统计信息"""
        try:
            self.match_stats = {
                "matches_started": 0,
                "matches_completed": 0,
                "matches_cancelled": 0,
                "average_match_time": 0.0,
                "match_errors": 0
            }
            print("✓ 匹配统计信息已重置")
        except Exception as e:
            print(f"✗ 匹配统计信息重置失败: {e}")
            
    def set_match_config(self, config: Dict[str, Any]) -> bool:
        """
        设置匹配配置
        
        Args:
            config: 匹配配置字典
            
        Returns:
            是否设置成功
        """
        try:
            self.match_config.update(config)
            print(f"✓ 匹配配置已更新: {self.match_config}")
            return True
        except Exception as e:
            print(f"✗ 匹配配置设置失败: {e}")
            return False
            
    def get_match_config(self) -> Dict[str, Any]:
        """
        获取匹配配置
        
        Returns:
            匹配配置字典
        """
        return self.match_config.copy()
        
    def _trigger_match_callback(self, callback_type: str, data: Dict[str, Any]):
        """
        触发匹配回调
        
        Args:
            callback_type: 回调类型
            data: 回调数据
        """
        try:
            if callback_type in self.match_callbacks:
                for callback in self.match_callbacks[callback_type]:
                    try:
                        callback(data)
                    except Exception as e:
                        print(f"✗ 匹配回调执行失败: {callback_type} - {e}")
        except Exception as e:
            print(f"✗ 匹配回调触发失败: {e}")
            
    def register_match_callback(self, callback_type: str, callback: callable):
        """
        注册匹配回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.match_callbacks:
                self.match_callbacks[callback_type].append(callback)
                print(f"✓ 匹配回调已注册: {callback_type}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 匹配回调注册失败: {e}")
            
    def unregister_match_callback(self, callback_type: str, callback: callable):
        """
        注销匹配回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.match_callbacks:
                if callback in self.match_callbacks[callback_type]:
                    self.match_callbacks[callback_type].remove(callback)
                    print(f"✓ 匹配回调已注销: {callback_type}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 匹配回调注销失败: {e}")