cmake_minimum_required(VERSION 3.8)
project(w6e_hand_hardware)

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Threads REQUIRED)

# 通信核心：不依赖 ROS，可在 macOS / Linux 单独编译测试
add_library(w6e_hand_io STATIC src/lq_bus.cpp src/hand_io.cpp)
set_target_properties(w6e_hand_io PROPERTIES POSITION_INDEPENDENT_CODE ON)
target_include_directories(w6e_hand_io PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
  $<INSTALL_INTERFACE:include>)
target_link_libraries(w6e_hand_io PUBLIC Threads::Threads)

add_executable(w6e_hand_io_test test/test_hand_io.cpp)
target_link_libraries(w6e_hand_io_test w6e_hand_io)
add_executable(hand_io_probe test/hand_io_probe.cpp)
target_link_libraries(hand_io_probe w6e_hand_io)

# 无 ROS 环境：cmake -S . -B build -DW6E_STANDALONE=ON
option(W6E_STANDALONE "只编译通信核心与测试（不需要 ROS）" OFF)
if(W6E_STANDALONE)
  enable_testing()
  add_test(NAME w6e_hand_io_test COMMAND w6e_hand_io_test)
  return()
endif()

find_package(ament_cmake REQUIRED)
find_package(hardware_interface REQUIRED)
find_package(pluginlib REQUIRED)
find_package(rclcpp REQUIRED)
find_package(rclcpp_lifecycle REQUIRED)
find_package(w6e_hand_interfaces REQUIRED)
find_package(std_msgs REQUIRED)
find_package(std_srvs REQUIRED)

add_library(w6e_hand_hardware SHARED src/w6e_hand_system.cpp)
# 只链 C++ typesupport；ament_target_dependencies(w6e_hand_interfaces) 会连带 generator_py，
# macOS 上 dlopen 插件时报 _PyBool_Type 未定义
target_link_libraries(w6e_hand_hardware
  w6e_hand_io
  w6e_hand_interfaces::w6e_hand_interfaces__rosidl_generator_cpp
  w6e_hand_interfaces::w6e_hand_interfaces__rosidl_typesupport_cpp)
ament_target_dependencies(w6e_hand_hardware
  hardware_interface pluginlib rclcpp rclcpp_lifecycle std_msgs std_srvs)
if(APPLE)
  # RoboStack：各消息包的 generator_py 带未定义 Python 符号，丢弃未用到的 dylib
  target_link_options(w6e_hand_hardware PRIVATE "LINKER:-dead_strip_dylibs")
endif()

pluginlib_export_plugin_description_file(hardware_interface w6e_hand_hardware_plugin.xml)

install(TARGETS w6e_hand_hardware w6e_hand_io
  ARCHIVE DESTINATION lib
  LIBRARY DESTINATION lib
  RUNTIME DESTINATION bin)
install(TARGETS hand_io_probe w6e_hand_io_test DESTINATION lib/${PROJECT_NAME})
install(DIRECTORY include/ DESTINATION include)

if(BUILD_TESTING)
  enable_testing()
  add_test(NAME w6e_hand_io_test COMMAND w6e_hand_io_test)
endif()

ament_export_include_directories(include)
ament_export_libraries(w6e_hand_hardware)
ament_export_dependencies(hardware_interface pluginlib rclcpp rclcpp_lifecycle)
ament_package()
