cmake_minimum_required(VERSION 3.25)

project(pymergetic_cppdantic LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include(GNUInstallDirs)

find_package(Python REQUIRED COMPONENTS Interpreter Development.Module)
execute_process(
    COMMAND "${Python_EXECUTABLE}" -c
        "import pathlib, pymergetic.easybind; print(pathlib.Path(pymergetic.easybind.__file__).resolve().parent / 'cmake' / 'easybind_pip.cmake')"
    OUTPUT_STRIP_TRAILING_WHITESPACE
    OUTPUT_VARIABLE _eb_pip
    COMMAND_ERROR_IS_FATAL ANY
)
include("${_eb_pip}")
easybind_pip_setup()
easybind_fetch_magic_enum()

nanobind_add_module(cppdantic__init__ NB_SHARED src/pymergetic/cppdantic/hello.cpp)
# Headers are #include <pymergetic/easybind/...> — include root is site-packages (parent of pymergetic/).
get_filename_component(_eb_include_root "${EASYBIND_PKG_DIR}/../.." ABSOLUTE)
target_include_directories(cppdantic__init__ PRIVATE "${_eb_include_root}")
target_link_libraries(cppdantic__init__ PRIVATE "${EASYBIND_CORE_LIB}")
easybind_pip_link_magic_enum(cppdantic__init__)

set_target_properties(cppdantic__init__ PROPERTIES
    OUTPUT_NAME "__init__"
    LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/pymergetic/cppdantic"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/pymergetic/cppdantic"
)

easybind_pip_set_rpath_next_to_easybind(cppdantic__init__ "${EASYBIND_PKG_DIR}")

# Stubs are committed; skip on Windows (nanobind_add_stub import often fails in CI — same as easybind).
if(NOT WIN32)
    set(_cppdantic_pyi "${CMAKE_CURRENT_SOURCE_DIR}/src/pymergetic/cppdantic/__init__.pyi")
    get_filename_component(_cppdantic_pyi_dir "${_cppdantic_pyi}" DIRECTORY)
    file(MAKE_DIRECTORY "${_cppdantic_pyi_dir}")
    nanobind_add_stub(cppdantic_stub
        MODULE pymergetic.cppdantic
        OUTPUT ${_cppdantic_pyi}
        PYTHON_PATH $<TARGET_FILE_DIR:cppdantic__init__>
        DEPENDS cppdantic__init__
    )
endif()

install(TARGETS cppdantic__init__
    LIBRARY DESTINATION pymergetic/cppdantic
    RUNTIME DESTINATION pymergetic/cppdantic
    ARCHIVE DESTINATION pymergetic/cppdantic
)
if(NOT WIN32)
    install(FILES ${_cppdantic_pyi} DESTINATION pymergetic/cppdantic)
endif()
