# The Python module gpflash._core: pybind11 bindings over the header-only library, compiled as ISO C++14 like the rest
# of the package. pyproject.toml drives this through scikit-build-core; only its install component, python, goes into
# the wheel, so the headers and CMake package files the root installs stay out of it.

find_package(Python 3.11 REQUIRED COMPONENTS Interpreter Development.Module)
find_package(pybind11 3.0 CONFIG REQUIRED)  # 3.0 for py::native_enum; pyproject.toml requires the same

pybind11_add_module(gpflash_python MODULE src/bindings.cpp)
set_target_properties(gpflash_python PROPERTIES OUTPUT_NAME _core)

# GpFlash::GpFlash carries every define, flag and library the headers need.
target_link_libraries(gpflash_python PRIVATE GpFlash::GpFlash)

# The README's "Compiling the headers" flags: -funroll-loops for batch posterior evaluation, -fno-math-errno so the
# kernels' math functions vectorize. Never -ffast-math, which core/Platform.hpp rejects.
target_compile_options(gpflash_python PRIVATE
    $<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-funroll-loops -fno-math-errno>)

# macOS: link libomp statically and export only the module's entry point. Two copies of libomp.dylib in one process,
# this module's and another library's such as torch's, abort (OMP: Error #15) or crash; a static, hidden copy does
# neither. Only this module is affected; GpFlash::GpFlash's consumers keep the dylib.
if(APPLE)
    get_target_property(gpflash_omp_link_libs OpenMP::OpenMP_CXX INTERFACE_LINK_LIBRARIES)
    set(gpflash_omp_static_link_libs "")
    foreach(gpflash_omp_lib IN LISTS gpflash_omp_link_libs)
        if(gpflash_omp_lib MATCHES "libomp\\.dylib$")
            string(REGEX REPLACE "\\.dylib$" ".a" gpflash_omp_static_lib "${gpflash_omp_lib}")
            # A source build against an OpenMP without the static library still builds; the wheels' tests
            # (test_openmp_isolation.py) refuse a module that links the dylib, so a release cannot ship one.
            if(EXISTS "${gpflash_omp_static_lib}")
                set(gpflash_omp_lib "${gpflash_omp_static_lib}")
            else()
                message(WARNING "No ${gpflash_omp_static_lib} beside the libomp.dylib FindOpenMP found, so the "
                        "module links the dylib and cannot share a process with another copy of libomp, such as "
                        "torch's. Homebrew's libomp provides both.")
            endif()
        endif()
        list(APPEND gpflash_omp_static_link_libs "${gpflash_omp_lib}")
    endforeach()
    set_property(TARGET OpenMP::OpenMP_CXX PROPERTY INTERFACE_LINK_LIBRARIES "${gpflash_omp_static_link_libs}")
    target_link_options(gpflash_python PRIVATE "LINKER:-exported_symbol,_PyInit__core")
endif()

install(TARGETS gpflash_python LIBRARY DESTINATION gpflash COMPONENT python)
