# Copyright 2026, Raffi Enficiaud.
#
# A cython extension linking a co-located shared library. Two things at once:
#
#  * cython_add_module turns a .pyx into an ordinary MODULE library target -- from
#    there on nothing in cmake-pip knows or cares that cython was involved;
#  * because it is an ordinary target, the dependency walk of python_package_add_target
#    stages libcython_dep_library next to it and the post-install relocation rewrites
#    the rpath. CMake strips the build rpath at install, so without that relocation the
#    import of the staged extension fails to locate the library.

cmake_minimum_required(VERSION 3.21)
set_property(GLOBAL PROPERTY USE_FOLDERS ON)

project(TestCMakePIPCythonSharedDependency)

# Development.Module: headers and platform-correct linking for extension modules;
# Python3_EXECUTABLE is pinned by cmake-pip to the driving interpreter, which is also
# the interpreter cython_add_module runs cython with.
find_package(Python3 COMPONENTS Interpreter Development.Module REQUIRED)

find_package(cmakepip REQUIRED)

# the shared library the extension depends on
add_library(cython_dep_library SHARED src/dep_library.cpp)
target_include_directories(cython_dep_library PUBLIC src)

# the cython module. CPLUS: the generated source is C++ (the library it calls is), so
# cython emits a .cpp and cmake compiles it as such. MODULE_NAME is the dotted name the
# module is imported under -- it is what the module reports as its __name__, and the
# file name of the extension follows its last component.
cython_add_module(TARGET cython_ext
                  SOURCE src/cython_ext.pyx
                  MODULE_NAME ext_cython_with_shared_dependency.cython_ext
                  CPLUS)

target_link_libraries(cython_ext PRIVATE cython_dep_library)

# from here on, identical to a hand-written extension
python_package_add_target(TARGET cython_ext
                          PYTHON_PACKAGE cython_dep_test
                          DESTINATION ext_cython_with_shared_dependency)
