cmake_minimum_required(VERSION 3.0.2)
project(action_core VERSION 0.1.0 LANGUAGES CXX)

# ========================================================
# Build mode detection
# ========================================================
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
  set(BUILDING_WITH_CATKIN TRUE)
  message(STATUS "Building action_core with Catkin")
else()
  set(BUILDING_WITH_CATKIN FALSE)
  message(STATUS "Building action_core with Standalone CMake")
endif()


# ========================================================
# C++ Standard
# ========================================================
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)


# ========================================================
# Common dependencies
# ========================================================
find_package(Boost REQUIRED COMPONENTS
  system
  filesystem
)

find_package(Threads REQUIRED)
find_package(yaml-cpp REQUIRED)

# tf3 không được build bởi workspace này (cài sẵn ở /usr/local/lib/libtf3.so). Handler dò cần nó để
# đọc frame thô và GHI lại frame đã lọc — xem ActionContext.
find_library(TF3_LIBRARY
  NAMES tf3
  PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu
)

if(NOT TF3_LIBRARY)
  message(FATAL_ERROR "tf3 not found — install tf3 (/usr/local/lib/libtf3.so) before building")
endif()


# ========================================================
# Standalone configuration
# ========================================================
if(NOT BUILDING_WITH_CATKIN)

  set(CMAKE_POSITION_INDEPENDENT_CODE ON)
  set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
  set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
  set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")

  # Test/action_core -> Test -> AMR_T800. Cây nguồn của nav core nằm ngay dưới đó.
  set(PNKX_NAV_CORE_SRC_DIR
    "${CMAKE_CURRENT_SOURCE_DIR}/../../.."
  )

  set(WORKSPACE_DEVEL_LIB_DIR
    "${CMAKE_CURRENT_SOURCE_DIR}/../../../../devel/lib"
  )

  file(GLOB STANDALONE_PACKAGE_INCLUDE_DIRS
    LIST_DIRECTORIES true

    ${PNKX_NAV_CORE_SRC_DIR}/*/include
    ${PNKX_NAV_CORE_SRC_DIR}/*/*/include
    ${PNKX_NAV_CORE_SRC_DIR}/*/*/*/include
    ${PNKX_NAV_CORE_SRC_DIR}/*/*/*/*/include
  )

  set(STANDALONE_INCLUDE_DIRS
    ${STANDALONE_PACKAGE_INCLUDE_DIRS}

    /opt/ros/noetic/include
    /usr/local/include
  )

  if(EXISTS ${WORKSPACE_DEVEL_LIB_DIR})
    link_directories(${WORKSPACE_DEVEL_LIB_DIR})
  endif()

  link_directories(
    /usr/local/lib
  )

  # Gói này KHÔNG kéo costmap/tf3: action không chạm bản đồ và không phát vận tốc (D8), nên năm
  # thư viện dưới đây là toàn bộ phụ thuộc runtime của nó.
  set(STANDALONE_LIBRARIES
    robot_cpp
    robot_time
    robot_xmlrpcpp
    robot_protocol_msgs
    robot_sensor_ports
  )

  include_directories(
    include
  )

  include_directories(SYSTEM
    ${STANDALONE_INCLUDE_DIRS}
    ${Boost_INCLUDE_DIRS}
  )


# ========================================================
# Catkin configuration
# ========================================================
else()

  find_package(catkin REQUIRED COMPONENTS
    robot_cpp
    robot_time
    robot_protocol_msgs
    robot_xmlrpcpp
    robot_sensor_ports
  )

  catkin_package(
    INCLUDE_DIRS
      include

    LIBRARIES
      action_core
      action_core_frame_sampler_action_handler
      action_core_wait_action_handler
      action_core_log_report_action_handler
      action_core_noop_action_handler

    CATKIN_DEPENDS
      robot_cpp
      robot_time
      robot_protocol_msgs
      robot_xmlrpcpp
      robot_sensor_ports

    DEPENDS
      Boost
  )

  include_directories(
    include
  )

  # Header của dependency vào dạng SYSTEM: gói này build với -Wall -Wextra, mà robot_cpp sinh hàng
  # trăm warning riêng của nó — để lẫn vào thì warning của chính gói này vô hình.
  include_directories(SYSTEM
    ${catkin_INCLUDE_DIRS}
    ${Boost_INCLUDE_DIRS}
  )

endif()


# ========================================================
# Core library
# ========================================================
add_library(action_core SHARED
  src/action_types.cpp
  src/action_registry.cpp
  src/pose_sample_filter.cpp
)

target_compile_options(action_core PRIVATE -Wall -Wextra)


if(BUILDING_WITH_CATKIN)

  add_dependencies(action_core
    ${${PROJECT_NAME}_EXPORTED_TARGETS}
    ${catkin_EXPORTED_TARGETS}
  )

  target_include_directories(action_core
    PUBLIC
      $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
      $<INSTALL_INTERFACE:include>

      ${Boost_INCLUDE_DIRS}
  )

  target_link_libraries(action_core
    PUBLIC
      ${catkin_LIBRARIES}

    PRIVATE
      Boost::boost
      Boost::system
      Boost::filesystem

      yaml-cpp

      Threads::Threads

      ${CMAKE_DL_LIBS}

      ${TF3_LIBRARY}
  )

else()

  target_include_directories(action_core
    PUBLIC
      $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
      $<INSTALL_INTERFACE:include>
  )

  # SYSTEM phải đứng ngay sau tên target. Include trong cây nguồn phải bọc BUILD_INTERFACE,
  # nếu không install(EXPORT) fail "prefixed in the source directory" khi package nằm in-tree.
  target_include_directories(action_core SYSTEM
    PUBLIC
      "$<BUILD_INTERFACE:${STANDALONE_INCLUDE_DIRS}>"
      ${Boost_INCLUDE_DIRS}
  )

  target_link_libraries(action_core
    PUBLIC
      ${STANDALONE_LIBRARIES}

    PRIVATE
      Boost::boost
      Boost::system
      Boost::filesystem

      yaml-cpp

      Threads::Threads

      ${CMAKE_DL_LIBS}

      ${TF3_LIBRARY}
  )

  # .so phải nằm ở root build dir như mission_adapters/recovery_core — PluginLoaderHelper chỉ tìm
  # theo PNKX_NAV_CORE_LIBRARY_PATH / build dir / devel/lib, không quét thư mục con của build tree.
  set_target_properties(action_core PROPERTIES
    LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
    BUILD_RPATH "${CMAKE_BINARY_DIR}"
    INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
  )

endif()


# ========================================================
# Action handler plugins
# ========================================================
#
# Mỗi handler là một .so riêng, nạp qua Boost.DLL theo khoá `library_path` trong YAML — KHÔNG link
# thẳng vào ai. Thêm một loại action mới = thêm một dòng ở đây + một dòng YAML.
set(ACTION_CORE_PLUGIN_TARGETS)

function(add_action_core_plugin target source)

  add_library(${target} SHARED ${source})

  target_compile_options(${target} PRIVATE -Wall -Wextra)

  add_dependencies(${target} action_core)

  set_target_properties(${target} PROPERTIES POSITION_INDEPENDENT_CODE ON)

  if(BUILDING_WITH_CATKIN)
    add_dependencies(${target}
      ${${PROJECT_NAME}_EXPORTED_TARGETS}
      ${catkin_EXPORTED_TARGETS}
    )

    target_include_directories(${target}
      PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        $<INSTALL_INTERFACE:include>
    )

    target_link_libraries(${target}
      PUBLIC
        action_core

      PRIVATE
        ${catkin_LIBRARIES}
        Boost::boost
        ${CMAKE_DL_LIBS}
        ${TF3_LIBRARY}
    )
  else()
    target_include_directories(${target}
      PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        $<INSTALL_INTERFACE:include>
    )

    target_include_directories(${target} SYSTEM
      PUBLIC
        "$<BUILD_INTERFACE:${STANDALONE_INCLUDE_DIRS}>"
        ${Boost_INCLUDE_DIRS}
    )

    target_link_libraries(${target}
      PUBLIC
        action_core

      PRIVATE
        ${STANDALONE_LIBRARIES}
        Boost::boost
        ${CMAKE_DL_LIBS}
        ${TF3_LIBRARY}
    )

    # Handler nạp qua Boost.DLL theo `library_path` trong YAML — .so phải ra root build dir,
    # nếu không PluginLoaderHelper báo "Library not found for symbol" dù build xanh.
    set_target_properties(${target} PROPERTIES
      LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
      BUILD_RPATH "${CMAKE_BINARY_DIR}"
      INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
    )
  endif()

  set(ACTION_CORE_PLUGIN_TARGETS
    ${ACTION_CORE_PLUGIN_TARGETS} ${target}
    PARENT_SCOPE
  )

endfunction()


# Bộ handler DEFAULT của gói. `wait` và `logReport` là hiện thực thật, chạy được trên robot thật —
# chúng không điều khiển thiết bị nào vì chính action đó không yêu cầu thiết bị nào. `noop` là stub
# mô phỏng, chỉ dành cho sim/dev.
add_action_core_plugin(action_core_frame_sampler_action_handler plugins/frame_sampler_action_handler.cpp)
add_action_core_plugin(action_core_wait_action_handler       plugins/wait_action_handler.cpp)
add_action_core_plugin(action_core_log_report_action_handler plugins/log_report_action_handler.cpp)
add_action_core_plugin(action_core_noop_action_handler       plugins/noop_action_handler.cpp)


# ========================================================
# Install
# ========================================================
if(BUILDING_WITH_CATKIN)

  install(TARGETS action_core ${ACTION_CORE_PLUGIN_TARGETS}
    ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
    LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
    RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
  )

  install(DIRECTORY include/${PROJECT_NAME}/
    DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
    FILES_MATCHING PATTERN "*.h"
  )

else()

  include(GNUInstallDirs)

  install(TARGETS action_core ${ACTION_CORE_PLUGIN_TARGETS}
    EXPORT ${PROJECT_NAME}-targets
    ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
  )

  install(EXPORT ${PROJECT_NAME}-targets
    FILE ${PROJECT_NAME}-targets.cmake
    NAMESPACE ${PROJECT_NAME}::
    DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}
  )

  install(DIRECTORY include/${PROJECT_NAME}/
    DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}
    FILES_MATCHING PATTERN "*.h"
  )

endif()


# ========================================================
# Tests
# ========================================================
# Tests are OFF by default in both build modes; enable with -DBUILD_ACTION_CORE_TESTS=ON.
option(BUILD_ACTION_CORE_TESTS "Build the action_core unit tests" OFF)

if(BUILD_ACTION_CORE_TESTS AND CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN)

  if(NOT COMMAND catkin_add_gtest)
    message(FATAL_ERROR "catkin_add_gtest NOT FOUND")
  endif()

  # Plugin giả cho ABI guard test: chỉ build cùng test, không install.
  add_action_core_plugin(action_core_test_stale_abi_handler test/plugins/stale_abi_action_handler.cpp)

  set(ACTION_CORE_TESTS
    action_registry_test
    noop_action_handler_test
    frame_sampler_test
    wait_action_handler_test
    log_report_action_handler_test
  )

  foreach(test_name ${ACTION_CORE_TESTS})
    catkin_add_gtest(${test_name} test/${test_name}.cpp)

    if(TARGET ${test_name})
      # catkin_add_gtest đặt target EXCLUDE_FROM_ALL; mở ra để binary có mặt sau `catkin_make`
      # thường, đúng quy trình verify của repo (chạy thẳng ./devel/lib/<pkg>/<test>).
      set_target_properties(${test_name} PROPERTIES EXCLUDE_FROM_ALL FALSE)

      target_compile_options(${test_name} PRIVATE -Wall -Wextra)

      target_include_directories(${test_name}
        PRIVATE
          ${CMAKE_CURRENT_SOURCE_DIR}/include
          ${CMAKE_CURRENT_SOURCE_DIR}/test
      )

      target_include_directories(${test_name} SYSTEM
        PRIVATE
          ${catkin_INCLUDE_DIRS}
      )

      # catkin_add_gtest dùng target_link_libraries dạng plain, nên phần bổ sung cũng phải plain.
      # Plugin KHÔNG được link thẳng: chúng chỉ export alias Boost.DLL và được nạp qua
      # ActionRegistry, đúng đường mà runtime đi.
      target_link_libraries(${test_name}
        action_core
        ${catkin_LIBRARIES}
        ${Boost_LIBRARIES}
        yaml-cpp
        pthread
        ${CMAKE_DL_LIBS}
        ${TF3_LIBRARY}
      )

      add_dependencies(${test_name} ${ACTION_CORE_PLUGIN_TARGETS})

      # Đường tới cây config test và thư mục .so, để binary tự trỏ đúng chỗ khi chạy qua ctest
      # (ctest không mang theo PNKX_NAV_CORE_CONFIG_DIR hay LD_LIBRARY_PATH của shell).
      target_compile_definitions(${test_name} PRIVATE
        ACTION_CORE_TEST_CONFIG_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test/config"
        ACTION_CORE_TEST_LIBRARY_DIR="${CATKIN_DEVEL_PREFIX}/lib"
      )
    endif()
  endforeach()

endif()
