"""
行为树示例
演示如何使用行为树插件创建和运行行为树
"""

def create_patrol_behavior_tree(plugin):
    """
    创建巡逻行为树示例
    """
    # 导入必要的节点类
    from ..nodes.control_nodes import SelectorNode, SequenceNode
    from ..nodes.decorator_nodes import RepeaterNode
    from ..nodes.leaf_nodes import ConditionNode, ActionNode
    
    # 创建根选择节点
    root = SelectorNode("Root")
    
    # 创建巡逻序列节点
    patrol_sequence = SequenceNode("Patrol")
    
    # 创建条件节点：检查是否需要巡逻
    need_patrol_condition = ConditionNode("NeedPatrol", 
                                         lambda bb: bb.get("need_patrol", True))
    
    # 创建动作节点：执行巡逻
    patrol_action = ActionNode("PatrolAction", 
                              lambda bb: print("执行巡逻动作") or True)
    
    # 创建重复节点：重复巡逻5次
    patrol_repeater = RepeaterNode(patrol_sequence, "PatrolRepeater", count=5)
    
    # 组装巡逻序列
    patrol_sequence.add_child(need_patrol_condition)
    patrol_sequence.add_child(patrol_action)
    
    # 创建休息序列节点
    rest_sequence = SequenceNode("Rest")
    
    # 创建条件节点：检查是否需要休息
    need_rest_condition = ConditionNode("NeedRest", 
                                       lambda bb: bb.get("need_rest", False))
    
    # 创建动作节点：执行休息
    rest_action = ActionNode("RestAction", 
                            lambda bb: print("执行休息动作") or True)
    
    # 组装休息序列
    rest_sequence.add_child(need_rest_condition)
    rest_sequence.add_child(rest_action)
    
    # 将子节点添加到根节点
    root.add_child(patrol_repeater)
    root.add_child(rest_sequence)
    
    # 创建行为树
    tree = plugin.create_behavior_tree("patrol_tree", root)
    
    # 创建黑板
    blackboard = plugin.create_blackboard("patrol_blackboard")
    
    # 设置黑板初始值
    blackboard.set("need_patrol", True)
    blackboard.set("need_rest", False)
    
    # 将黑板关联到行为树
    tree.set_blackboard(blackboard)
    
    return tree, blackboard

def run_patrol_example(plugin):
    """
    运行巡逻行为树示例
    """
    print("=== 行为树示例：巡逻AI ===")
    
    # 创建行为树和黑板
    tree, blackboard = create_patrol_behavior_tree(plugin)
    
    # 运行行为树
    for i in range(10):
        print(f"\n--- 第 {i+1} 次执行 ---")
        status = tree.run()
        print(f"行为树执行结果: {status.value}")
        
        # 每次执行后切换状态
        if i % 3 == 2:
            blackboard.set("need_patrol", not blackboard.get("need_patrol", True))
            blackboard.set("need_rest", not blackboard.get("need_rest", False))
            print("切换巡逻/休息状态")