# SPDX-License-Identifier: MPL-2.0
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was
# not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
# The Python bindings: the extension module _lunopt (nanobind), the package lunopt with the pygmo algorithm, and their
# tests. Needs a Python 3.12+ with development headers and nanobind (the presets use the repository's .venv-python:
# uv venv --python 3.12 .venv-python; uv pip install --python .venv-python/bin/python nanobind==3.1.0 pygmo).
find_package(Python 3.12 COMPONENTS Interpreter Development.Module)
if(NOT Python_FOUND)
    message(WARNING "LUNOPT_PYTHON: no Python 3.12+ with development headers; the bindings are not built")
    return()
endif()
execute_process(COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
    OUTPUT_VARIABLE nanobind_ROOT OUTPUT_STRIP_TRAILING_WHITESPACE RESULT_VARIABLE _nanobind_missing)
if(_nanobind_missing)
    message(WARNING "LUNOPT_PYTHON: nanobind is not installed for ${Python_EXECUTABLE}; the bindings are not built")
    return()
endif()
find_package(nanobind CONFIG REQUIRED)

set(_package "${PROJECT_BINARY_DIR}/python/lunopt")
# Its own domain: another project's module may bind LUNOPT's types too (its vendored copy), and both load in one
# process.
nanobind_add_module(_lunopt NB_STATIC NB_DOMAIN lunopt src/module.cpp)
target_link_libraries(_lunopt PRIVATE lunopt::lunopt)
target_compile_features(_lunopt PRIVATE cxx_std_23)
set_target_properties(_lunopt PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${_package}")
target_compile_definitions(_lunopt PRIVATE LUNOPT_VERSION="${PROJECT_VERSION}")
if(DEFINED _lunopt_warnings)
    target_compile_options(_lunopt PRIVATE ${_lunopt_warnings})
endif()
# GCC 16.2's libstdc++ is newer than the system's, which Python may have loaded already (numpy): linked into the module,
# its symbols hidden.
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
    target_link_options(_lunopt PRIVATE -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL)
    # GCC optimising sees nanobind's casters' std::optional members as maybe uninitialised where they are inlined into
    # the bindings: false positives in nanobind's code paths.
    target_compile_options(_lunopt PRIVATE -Wno-maybe-uninitialized)
endif()
# nanobind's headers as system headers, so that LUNOPT's warnings apply to the bindings only.
set_target_properties(nanobind-static PROPERTIES SYSTEM ON)
foreach(_file IN ITEMS __init__.py algorithm.py)
    configure_file("lunopt/${_file}" "${_package}/${_file}" COPYONLY)
endforeach()

if(SKBUILD)
    install(TARGETS _lunopt LIBRARY DESTINATION lunopt)
endif()

if(LUNOPT_BUILD_TESTS)
    add_test(NAME "lunopt: Python"
        COMMAND "${Python_EXECUTABLE}" -m unittest discover -s "${CMAKE_CURRENT_SOURCE_DIR}/tests" -v)
    set_tests_properties("lunopt: Python" PROPERTIES ENVIRONMENT "PYTHONPATH=${PROJECT_BINARY_DIR}/python")
endif()
