cmake_minimum_required(VERSION 3.18...3.30)
project(pymarvin LANGUAGES CXX)
if(NOT CMAKE_SYSTEM_NAME MATCHES "^(Linux|Windows)$")
  message(FATAL_ERROR "pymarvin supports Linux and Windows")
endif()
find_package(Python 3.10 REQUIRED COMPONENTS Interpreter Development.Module)
find_package(nanobind CONFIG REQUIRED)
find_package(Threads REQUIRED)
option(PYMARVIN_ENABLE_COVERAGE "Instrument binding code for GCC coverage" OFF)
if(PYMARVIN_ENABLE_COVERAGE AND NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
  message(FATAL_ERROR "PYMARVIN_ENABLE_COVERAGE requires GCC")
endif()
foreach(sdk IN ITEMS control kinematics interference)
  if(sdk STREQUAL "control")
    set(module _control)
    file(GLOB sdk_sources CONFIGURE_DEPENDS "src/sdk/control/*.cpp")
    set(sdk_include_dir "src/sdk/control")
  elseif(sdk STREQUAL "kinematics")
    set(module _kinematics)
    file(GLOB sdk_sources CONFIGURE_DEPENDS "src/sdk/kinematics/*.cpp")
    set(sdk_include_dir "src/sdk/kinematics")
  else()
    set(module _interference)
    file(GLOB sdk_sources CONFIGURE_DEPENDS
      "src/sdk/interference/Interf/*.cpp"
      "src/sdk/interference/FxCfg/*.cpp")
    set(sdk_include_dir "src/sdk/interference/Interf" "src/sdk/interference/FxCfg")
  endif()
  nanobind_add_module(${module} src/bindings/${module}.cpp ${sdk_sources})
  target_compile_features(${module} PRIVATE cxx_std_17)
  target_include_directories(${module} PRIVATE ${sdk_include_dir} src/bindings)
  target_link_libraries(${module} PRIVATE Threads::Threads ${CMAKE_DL_LIBS})
  if(WIN32)
    target_compile_definitions(${module} PRIVATE CMPL_WIN WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS)
    target_link_libraries(${module} PRIVATE ws2_32 winmm)
    if(MSVC)
      target_compile_options(${module} PRIVATE /utf-8)
    endif()
  else()
    # CMPL_LIN selects the SDK's POSIX sockets and shared-memory implementation.
    target_compile_definitions(${module} PRIVATE CMPL_LIN)
    if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
      target_link_libraries(${module} PRIVATE rt)
    endif()
  endif()
  if(PYMARVIN_ENABLE_COVERAGE)
    # Measure only binding translation units and their inline helpers.
    set_source_files_properties("src/bindings/${module}.cpp" PROPERTIES
      COMPILE_OPTIONS "--coverage;-O0;-g;-fprofile-update=atomic")
    target_link_options(${module} PRIVATE --coverage)
  endif()
  # SDKs define common helper names; keep each extension's symbols separate.
  set_target_properties(${module} PROPERTIES CXX_VISIBILITY_PRESET hidden
    VISIBILITY_INLINES_HIDDEN ON)
  if(UNIX AND sdk STREQUAL "control")
    target_link_options(${module} PRIVATE "LINKER:--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/bindings/control.exports")
  endif()
  install(TARGETS ${module} LIBRARY DESTINATION pymarvin RUNTIME DESTINATION pymarvin)
endforeach()
