"""
行为树插件
提供完整的行为树功能用于实现AI决策逻辑
包含节点系统、黑板系统、管理器等完整功能
"""

from plugins.plugin_manager import BasePlugin
from typing import Dict, Optional, Any

class Plugin(BasePlugin):
    """
    行为树插件
    提供完整的行为树功能用于实现AI决策逻辑
    """
    
    def __init__(self, plugin_manager, name):
        super().__init__(plugin_manager, name)
        self.config = {
            "version": "1.0.0",
            "author": "EG Team",
            "description": "行为树插件，用于实现AI决策逻辑，包含完整的节点系统、黑板系统和管理器"
        }
        self.behavior_trees = {}
        self.blackboards = {}
        self.tree_manager = None
        self.blackboard_manager = None
        self.is_initialized = False
        
    def initialize(self) -> bool:
        """
        初始化插件
        """
        if self.is_initialized:
            return True
            
        try:
            # 导入核心模块
            from plugins.user.behavior_tree.core.behavior_tree import BehaviorTreeManager
            from plugins.user.behavior_tree.core.blackboard import BlackboardManager
            
            # 创建管理器实例
            self.tree_manager = BehaviorTreeManager()
            self.blackboard_manager = BlackboardManager()
            
            print(f"初始化行为树插件: {self.name}")
            self.is_initialized = True
            return True
            
        except Exception as e:
            print(f"行为树插件初始化失败: {e}")
            import traceback
            traceback.print_exc()
            return False
        
    def enable(self) -> bool:
        """
        启用插件
        """
        if not super().enable():
            return False
            
        if not self.is_initialized:
            if not self.initialize():
                return False
                
        print(f"启用行为树插件: {self.name}")
        return True
        
    def disable(self) -> bool:
        """
        禁用插件
        """
        if not super().disable():
            return False
            
        # 停止所有激活的行为树
        if self.tree_manager:
            self.tree_manager.active_trees.clear()
            
        print(f"禁用行为树插件: {self.name}")
        return True
        
    def finalize(self) -> None:
        """
        清理插件资源
        """
        print(f"清理行为树插件资源: {self.name}")
        
        try:
            # 停止所有激活的行为树
            if self.tree_manager:
                self.tree_manager.active_trees.clear()
                
            # 清理资源
            self.behavior_trees.clear()
            self.blackboards.clear()
            self.tree_manager = None
            self.blackboard_manager = None
            self.is_initialized = False
            
            print(f"行为树插件资源清理完成: {self.name}")
            
        except Exception as e:
            print(f"清理行为树插件资源失败: {e}")
            import traceback
            traceback.print_exc()
        
    def create_behavior_tree(self, name: str, root_node) -> Optional['BehaviorTree']:
        """
        创建行为树
        """
        try:
            from plugins.user.behavior_tree.core.behavior_tree import BehaviorTree
            tree = BehaviorTree(name, root_node)
            self.behavior_trees[name] = tree
            
            # 添加到管理器
            if self.tree_manager:
                self.tree_manager.add_tree(name, tree)
                
            return tree
        except Exception as e:
            print(f"创建行为树失败: {e}")
            return None
        
    def create_blackboard(self, name: str, **kwargs) -> Optional['Blackboard']:
        """
        创建黑板
        """
        try:
            if self.blackboard_manager:
                blackboard = self.blackboard_manager.create_blackboard(name, **kwargs)
                self.blackboards[name] = blackboard
                return blackboard
            else:
                from plugins.user.behavior_tree.core.blackboard import Blackboard
                blackboard = Blackboard(name, **kwargs)
                self.blackboards[name] = blackboard
                return blackboard
        except Exception as e:
            print(f"创建黑板失败: {e}")
            return None
            
    def get_behavior_tree(self, name: str) -> Optional['BehaviorTree']:
        """
        获取行为树实例
        """
        return self.behavior_trees.get(name)
        
    def get_blackboard(self, name: str) -> Optional['Blackboard']:
        """
        获取黑板实例
        """
        return self.blackboards.get(name)
        
    def remove_behavior_tree(self, name: str) -> bool:
        """
        移除行为树
        """
        if name in self.behavior_trees:
            # 从管理器移除
            if self.tree_manager:
                self.tree_manager.remove_tree(name)
            del self.behavior_trees[name]
            return True
        return False
        
    def remove_blackboard(self, name: str) -> bool:
        """
        移除黑板
        """
        if name in self.blackboards:
            # 从管理器移除
            if self.blackboard_manager:
                self.blackboard_manager.remove_blackboard(name)
            del self.blackboards[name]
            return True
        return False
        
    def get_tree_manager(self) -> Optional['BehaviorTreeManager']:
        """
        获取行为树管理器
        """
        return self.tree_manager
        
    def get_blackboard_manager(self) -> Optional['BlackboardManager']:
        """
        获取黑板管理器
        """
        return self.blackboard_manager
        
    def update_all_trees(self, dt: float = None) -> None:
        """
        更新所有激活的行为树
        """
        if self.tree_manager:
            self.tree_manager.update_all(dt)
            
    def get_tree_statistics(self, name: str) -> Optional[Dict[str, Any]]:
        """
        获取行为树统计信息
        """
        if self.tree_manager:
            return self.tree_manager.get_tree_stats(name)
        return None
        
    def get_all_statistics(self) -> Dict[str, Dict[str, Any]]:
        """
        获取所有行为树统计信息
        """
        if self.tree_manager:
            return self.tree_manager.get_all_stats()
        return {}
        
    def reset_all_trees(self) -> None:
        """
        重置所有行为树
        """
        if self.tree_manager:
            # 重置管理器中的所有树
            for tree in self.tree_manager.trees.values():
                tree.reset()
                
            # 重置插件中的所有树
            for tree in self.behavior_trees.values():
                tree.reset()

# 兼容性接口
Plugin = Plugin