#include <gtest/gtest.h>
#include <rclcpp/rclcpp.hpp>
#include <behaviortree_cpp/bt_factory.h>
#include <filesystem>
#include "brain/bt_registry.hpp"

TEST(BTRegistry, BuildTreeFromXmlFile)
{
  rclcpp::init(0, nullptr);
  auto node = std::make_shared<rclcpp::Node>("test_bt_registry_xml_node");
  BT::BehaviorTreeFactory factory;
  BTRegistry reg(factory, node.get());

  // Register a dummy TestAction handler so the XML leaf resolves.
  BTActionHandlers handlers;
  bool start_called = false;
  handlers.on_start = [&](rclcpp::Node *, BT::TreeNode &) {
    start_called = true; return BT::NodeStatus::SUCCESS; };
  reg.register_bt_action("TestAction", handlers);

  // Derive path to sample_tree.xml located alongside this test source file.
  std::filesystem::path xml_path = std::filesystem::path(__FILE__).parent_path() / "sample_tree.xml";
  BT::Tree tree;
  ASSERT_TRUE(reg.build_tree_from_xml_file(xml_path.string(), tree));
  tree.tickWhileRunning();
  EXPECT_TRUE(start_called);
  rclcpp::shutdown();
}

TEST(BTRegistry, BuildTreeFromXmlText)
{
  rclcpp::init(0, nullptr);
  auto node = std::make_shared<rclcpp::Node>("test_bt_registry_xml_text_node");
  BT::BehaviorTreeFactory factory;
  BTRegistry reg(factory, node.get());
  BTActionHandlers handlers;
  bool running_called = false;
  handlers.on_running = [&](rclcpp::Node *, BT::TreeNode &) {
    running_called = true; return BT::NodeStatus::SUCCESS; };
  reg.register_bt_action("TestAction", handlers);

  const std::string xml = R"(<root BTCPP_format=\"4\"><BehaviorTree ID=\"T\"><Sequence name=\"root\"><TestAction name=\"X\"/></Sequence></BehaviorTree></root>)";
  BT::Tree tree;
  ASSERT_TRUE(reg.build_tree_from_xml_text(xml, tree));
  tree.tickWhileRunning();
  EXPECT_TRUE(running_called);
  rclcpp::shutdown();
}
