# set source files
set(SRC
    common.cpp
    mcs.cpp
    pathset.cpp
    sdp.cpp
    utils.cpp
    bindings.cpp
)

# find pybind11
include(FetchContent)
FetchContent_Declare(
  pybind11
  GIT_REPOSITORY https://github.com/pybind/pybind11.git
  GIT_TAG        v2.13.6
)
FetchContent_MakeAvailable(pybind11)

# find OpenMP
find_package(OpenMP)

# pybind11 module
pybind11_add_module(pyrbd3_cpp ${SRC})
set_target_properties(pyrbd3_cpp PROPERTIES
    LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
)

# Link OpenMP if found
if (OpenMP_CXX_FOUND)
  target_link_libraries(pyrbd3_cpp PUBLIC OpenMP::OpenMP_CXX)
elseif (APPLE)
  set(_libomp_prefix "${CMAKE_PREFIX_PATH}")
  if (NOT _libomp_prefix)
    if (EXISTS "/opt/homebrew/opt/libomp")
      set(_libomp_prefix "/opt/homebrew/opt/libomp")
    elseif (EXISTS "/usr/local/opt/libomp")
      set(_libomp_prefix "/usr/local/opt/libomp")
    endif()
  endif()

  find_path(LIBOMP_INCLUDE omp.h HINTS "${_libomp_prefix}/include")
  find_library(LIBOMP_LIBRARY NAMES omp libomp HINTS "${_libomp_prefix}/lib")

  if (LIBOMP_INCLUDE AND LIBOMP_LIBRARY)
    target_compile_options(pyrbd3_cpp PRIVATE -Xpreprocessor -fopenmp)
    target_include_directories(pyrbd3_cpp PRIVATE "${LIBOMP_INCLUDE}")
    target_link_libraries(pyrbd3_cpp PRIVATE "${LIBOMP_LIBRARY}")
    set_target_properties(pyrbd3_cpp PROPERTIES
      BUILD_RPATH "${_libomp_prefix}/lib"
      INSTALL_RPATH "@loader_path;@loader_path/..;${_libomp_prefix}/lib")
  else()
    message(FATAL_ERROR "libomp not found. Set CMAKE_PREFIX_PATH or brew install libomp.")
  endif()
else()
  message(FATAL_ERROR "OpenMP not found on this platform.")
endif()

# set compile options
target_compile_options(pyrbd3_cpp PRIVATE -Wall -O3)

# set march=native for non-Apple platforms
if(NOT APPLE)
  target_compile_options(pyrbd3_cpp PRIVATE -march=native)
endif()

# set the include directories
target_include_directories(pyrbd3_cpp PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<INSTALL_INTERFACE:include>
)

# clean target
add_custom_target(distclean
    COMMAND ${CMAKE_COMMAND} -E remove_directory CMakeFiles
    COMMAND ${CMAKE_COMMAND} -E remove CMakeCache.txt
    COMMAND ${CMAKE_COMMAND} -E remove cmake_install.cmake
    COMMAND ${CMAKE_COMMAND} -E remove Makefile
    COMMAND ${CMAKE_COMMAND} -E remove -f ${CMAKE_CURRENT_SOURCE_DIR}/*.so
    COMMAND ${CMAKE_COMMAND} -E remove_directory _deps
    COMMENT "Removing all build files"
)

# install target
install(TARGETS pyrbd3_cpp
    LIBRARY DESTINATION pyrbd3/_core
    RUNTIME DESTINATION pyrbd3/_core
)