cmake_minimum_required(VERSION 3.24...3.28)

set(CSP_NUMERICAL_PROFILE "portable-lp64" CACHE STRING "Numerical provider profile")
option(CSP_AUTO_DEPENDENCIES "Prepare the pinned native dependencies during configuration" ON)
if(CSP_AUTO_DEPENDENCIES AND CSP_NUMERICAL_PROFILE STREQUAL "portable-lp64")
    include(cmake/PrepareNativeDependencies.cmake)
endif()

if(NOT SKBUILD_PROJECT_NAME)
    set(SKBUILD_PROJECT_NAME c_spikes)
    set(SKBUILD_PROJECT_VERSION 0.0.0)
endif()
project(${SKBUILD_PROJECT_NAME} VERSION ${SKBUILD_PROJECT_VERSION} LANGUAGES C CXX)
if(MSVC)
    include(cmake/WindowsOpenMP.cmake)
elseif(APPLE)
    include(cmake/AppleOpenMP.cmake)
endif()

set(CMAKE_POSITION_INDEPENDENT_CODE ON)
# Kokkos 5 requires C++20 in both host and CUDA translation units.
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CUDA_STANDARD 20)
set(CMAKE_CUDA_STANDARD_REQUIRED ON)

set(PGAS_BUILD_GPU "OFF" CACHE STRING "Build PGAS GPU backend (AUTO, ON, OFF).")
set_property(CACHE PGAS_BUILD_GPU PROPERTY STRINGS AUTO ON OFF)
if(NOT PGAS_BUILD_GPU MATCHES "^(AUTO|ON|OFF)$")
    message(FATAL_ERROR "PGAS_BUILD_GPU must be AUTO, ON or OFF")
endif()
set(_csp_combined_default OFF)
if(PGAS_BUILD_GPU STREQUAL "ON")
    set(_csp_combined_default ON)
endif()
option(CSP_COMBINED_WHEEL "Build independent CPU and CUDA backends in one Python wheel" ${_csp_combined_default})
if(CSP_COMBINED_WHEEL)
    if(NOT PGAS_BUILD_GPU STREQUAL "ON")
        message(FATAL_ERROR "CSP_COMBINED_WHEEL requires PGAS_BUILD_GPU=ON")
    endif()
    include(cmake/CombinedWheel.cmake)
    return()
endif()
option(Kokkos_ENABLE_SERIAL "Enable Kokkos Serial" ON)
option(Kokkos_ENABLE_OPENMP "Enable Kokkos OpenMP (required by CPU PGAS)" ON)
option(Kokkos_ENABLE_CUDA "Enable Kokkos CUDA" OFF)
if(PGAS_BUILD_GPU STREQUAL "ON")
    set(Kokkos_ENABLE_CUDA ON CACHE BOOL "Enable Kokkos CUDA" FORCE)
endif()
if(Kokkos_ENABLE_CUDA)
    # Native CMake CUDA compilation also works with MSVC; nvcc_wrapper does not.
    set(Kokkos_ENABLE_COMPILE_AS_CMAKE_LANGUAGE ON CACHE BOOL "Use CMake CUDA language" FORCE)
    enable_language(CUDA)
    include(cmake/CudaArchitectures.cmake)
    add_compile_options($<$<COMPILE_LANGUAGE:CUDA>:--expt-relaxed-constexpr>)
    find_package(OpenMP REQUIRED COMPONENTS CXX)
    separate_arguments(_csp_openmp_flags NATIVE_COMMAND "${OpenMP_CXX_FLAGS}")
    foreach(flag IN LISTS _csp_openmp_flags)
        add_compile_options("$<$<COMPILE_LANGUAGE:CUDA>:-Xcompiler=${flag}>")
    endforeach()
endif()
if(MSVC)
    add_compile_definitions(NOMINMAX _USE_MATH_DEFINES)
endif()

option(C_SPIKES_BUILD_OASIS "Build the OASIS native extension." ON)
option(C_SPIKES_OBSERVATIONAL_DIAGNOSTICS "Enable optional numerical observations and context reporting." OFF)
add_library(csp_diagnostics_config INTERFACE)
target_compile_definitions(csp_diagnostics_config INTERFACE
    C_SPIKES_OBSERVATIONAL_DIAGNOSTICS=$<BOOL:${C_SPIKES_OBSERVATIONAL_DIAGNOSTICS}>)

option(CSP_NATIVE_CORE_INSTALL "Enable the qualified opt-in native-core installation profile." OFF)

if(C_SPIKES_BUILD_OASIS)
    find_package(Python COMPONENTS Interpreter Development.Module NumPy REQUIRED)

    Python_add_library(oasis_methods MODULE src/c_spikes/oasis/oasis_methods.cpp WITH_SOABI)
    target_compile_features(oasis_methods PRIVATE cxx_std_11)
    target_compile_definitions(oasis_methods PRIVATE NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION)
    target_link_libraries(oasis_methods PRIVATE Python::Module Python::NumPy)
endif()

add_subdirectory(dependencies)

find_package(pybind11 CONFIG REQUIRED)
if(CSP_NUMERICAL_PROFILE STREQUAL "linux-x86_64-lp64-serial")
    include(cmake/PinnedNumericalProvider.cmake)
elseif(CSP_NUMERICAL_PROFILE STREQUAL "portable-lp64")
    include(cmake/PortableNumericalProvider.cmake)
else()
    message(FATAL_ERROR "Unknown CSP_NUMERICAL_PROFILE: ${CSP_NUMERICAL_PROFILE}")
endif()
find_package(jsoncpp CONFIG REQUIRED)
find_package(GSL REQUIRED)
find_package(OpenMP REQUIRED COMPONENTS CXX)
find_package(Kokkos REQUIRED)

file(GLOB PGAS_SRCS CONFIGURE_DEPENDS src/c_spikes/pgas/*.cpp)
list(REMOVE_ITEM PGAS_SRCS "${CMAKE_SOURCE_DIR}/src/c_spikes/pgas/bindings.cpp")

#set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G -lineinfo") # for debugging CUDA code

# Build-tree library paths must not leak into distributed wheels.
set(CMAKE_INSTALL_RPATH "")
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
if(APPLE)
    # Editable installs need their prepared runtimes. Delocate resolves these
    # paths, bundles the dylibs and removes external rpaths for release wheels.
    set(CMAKE_INSTALL_RPATH "${_csp_openmp_root}/lib;${CMAKE_Fortran_IMPLICIT_LINK_DIRECTORIES}")
endif()

set(_pgas_build_gpu OFF)
if(PGAS_BUILD_GPU STREQUAL "ON")
    if(NOT Kokkos_ENABLE_CUDA)
        message(FATAL_ERROR "PGAS_BUILD_GPU=ON but Kokkos CUDA backend is not enabled.")
    endif()
    set(_pgas_build_gpu ON)
elseif(PGAS_BUILD_GPU STREQUAL "OFF")
    set(_pgas_build_gpu OFF)
else()
    if(Kokkos_ENABLE_CUDA)
        set(_pgas_build_gpu ON)
    endif()
endif()

set(PGAS_COMMON_LIBS csp_diagnostics_config JsonCpp::JsonCpp GSL::gsl GSL::gslcblas csp_numerical_provider OpenMP::OpenMP_CXX Kokkos::kokkos)

if(Kokkos_ENABLE_CUDA)
    set_source_files_properties(${PGAS_SRCS} src/c_spikes/pgas/bindings.cpp
        tests/native/test_ancestor_sampler.cpp tests/native/test_selected_trajectory.cpp
        tests/native/terminal_weight_copy.cpp PROPERTIES LANGUAGE CUDA)
endif()

option(C_SPIKES_TEST_RESAMPLING "Build focused native ancestor sampling checks." OFF)
if(C_SPIKES_TEST_RESAMPLING)
    enable_testing()
    add_executable(test_ancestor_cpu tests/native/test_ancestor_sampler.cpp)
    target_compile_definitions(test_ancestor_cpu PRIVATE USE_GPU=0)
    target_include_directories(test_ancestor_cpu PRIVATE src/c_spikes/pgas/include)
    target_link_libraries(test_ancestor_cpu PRIVATE GSL::gsl GSL::gslcblas Kokkos::kokkos)
    add_test(NAME ancestor_cpu COMMAND test_ancestor_cpu)
    add_executable(test_selected_cpu tests/native/test_selected_trajectory.cpp $<TARGET_OBJECTS:pgas_obj_cpu>)
    target_compile_definitions(test_selected_cpu PRIVATE USE_GPU=0)
    target_include_directories(test_selected_cpu PRIVATE src/c_spikes/pgas/include)
    target_link_libraries(test_selected_cpu PRIVATE ${PGAS_COMMON_LIBS})
    add_test(NAME selected_cpu COMMAND test_selected_cpu ${CMAKE_SOURCE_DIR}/src/c_spikes/pgas/20230525_gold.dat)
    if(_pgas_build_gpu)
        add_executable(test_ancestor_gpu tests/native/test_ancestor_sampler.cpp)
        target_compile_definitions(test_ancestor_gpu PRIVATE USE_GPU=1)
        target_include_directories(test_ancestor_gpu PRIVATE src/c_spikes/pgas/include)
        target_link_libraries(test_ancestor_gpu PRIVATE GSL::gsl GSL::gslcblas Kokkos::kokkos)
        add_test(NAME ancestor_gpu COMMAND test_ancestor_gpu)
        add_executable(test_selected_gpu tests/native/test_selected_trajectory.cpp $<TARGET_OBJECTS:pgas_obj_gpu>)
        target_compile_definitions(test_selected_gpu PRIVATE USE_GPU=1)
        target_include_directories(test_selected_gpu PRIVATE src/c_spikes/pgas/include)
        target_link_libraries(test_selected_gpu PRIVATE ${PGAS_COMMON_LIBS})
        add_test(NAME selected_gpu COMMAND test_selected_gpu ${CMAKE_SOURCE_DIR}/src/c_spikes/pgas/20230525_gold.dat)
    endif()
endif()

add_library(pgas_obj_cpu OBJECT ${PGAS_SRCS})
target_compile_definitions(pgas_obj_cpu PRIVATE USE_GPU=0)
target_compile_options(pgas_obj_cpu PRIVATE $<$<COMPILE_LANG_AND_ID:CXX,GNU,Clang>:-Wno-error=cpp>)
target_include_directories(pgas_obj_cpu PRIVATE src/c_spikes/pgas/include)
target_link_libraries(pgas_obj_cpu PRIVATE ${PGAS_COMMON_LIBS})

pybind11_add_module(pgas_bound_cpu MODULE src/c_spikes/pgas/bindings.cpp $<TARGET_OBJECTS:pgas_obj_cpu> NO_EXTRAS)
target_compile_options(pgas_bound_cpu PRIVATE $<$<COMPILE_LANG_AND_ID:CXX,GNU,Clang>:-Wno-error=cpp>)
target_compile_definitions(pgas_bound_cpu PRIVATE USE_GPU=0 PGAS_PYBIND_MODULE=pgas_bound_cpu)
target_include_directories(pgas_bound_cpu PRIVATE src/c_spikes/pgas/include)
target_link_libraries(pgas_bound_cpu PRIVATE ${PGAS_COMMON_LIBS})
csp_isolate_python_module(pgas_bound_cpu)

if(_pgas_build_gpu)
    add_library(pgas_obj_gpu OBJECT ${PGAS_SRCS})
    target_compile_definitions(pgas_obj_gpu PRIVATE USE_GPU=1)
    target_compile_options(pgas_obj_gpu PRIVATE $<$<COMPILE_LANG_AND_ID:CXX,GNU,Clang>:-Wno-error=cpp>)
    target_include_directories(pgas_obj_gpu PRIVATE src/c_spikes/pgas/include)
    target_link_libraries(pgas_obj_gpu PRIVATE ${PGAS_COMMON_LIBS})

    pybind11_add_module(pgas_bound_gpu MODULE src/c_spikes/pgas/bindings.cpp $<TARGET_OBJECTS:pgas_obj_gpu> NO_EXTRAS)
    target_compile_options(pgas_bound_gpu PRIVATE $<$<COMPILE_LANG_AND_ID:CXX,GNU,Clang>:-Wno-error=cpp>)
    target_compile_definitions(pgas_bound_gpu PRIVATE USE_GPU=1 PGAS_PYBIND_MODULE=pgas_bound_gpu)
    target_include_directories(pgas_bound_gpu PRIVATE src/c_spikes/pgas/include)
    target_link_libraries(pgas_bound_gpu PRIVATE ${PGAS_COMMON_LIBS})
    csp_isolate_python_module(pgas_bound_gpu)
endif()

install(TARGETS pgas_bound_cpu DESTINATION ${SKBUILD_PROJECT_NAME}/pgas COMPONENT CSPPython)
if(_pgas_build_gpu)
    install(TARGETS pgas_bound_gpu DESTINATION ${SKBUILD_PROJECT_NAME}/pgas COMPONENT CSPPython)
endif()
if(C_SPIKES_BUILD_OASIS)
    install(
        TARGETS oasis_methods
        LIBRARY DESTINATION ${SKBUILD_PROJECT_NAME}/oasis COMPONENT CSPPython
        RUNTIME DESTINATION ${SKBUILD_PROJECT_NAME}/oasis COMPONENT CSPPython
    )
endif()

if(WIN32 AND SKBUILD_STATE STREQUAL "editable" AND CSP_NUMERICAL_PROFILE STREQUAL "portable-lp64")
    # Editable installs do not go through delvewheel. Keep the pinned runtime
    # DLLs beside the extensions so imports work in an ordinary Python process.
    # Distributable wheels still use delvewheel's dependency repair/isolation.
    install(DIRECTORY "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/bin/"
        DESTINATION c_spikes/pgas COMPONENT CSPPython FILES_MATCHING PATTERN "*.dll")
    if(_pgas_build_gpu)
        find_package(CUDAToolkit REQUIRED)
        install(DIRECTORY "${CUDAToolkit_BIN_DIR}/"
            DESTINATION c_spikes/pgas COMPONENT CSPPython FILES_MATCHING PATTERN "cudart64*.dll")
    endif()
endif()

if(CSP_NUMERICAL_PROFILE STREQUAL "portable-lp64")
    set(_csp_notice_dependencies gsl jsoncpp openblas lapack-reference)
    if(WIN32)
        list(APPEND _csp_notice_dependencies vcpkg-gfortran)
    endif()
    if(WIN32 OR APPLE)
        list(APPEND _csp_notice_dependencies csp-openmp)
    endif()
    foreach(dependency IN LISTS _csp_notice_dependencies)
        set(notice "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/share/${dependency}/copyright")
        if(NOT EXISTS "${notice}")
            message(FATAL_ERROR "Missing native dependency notice: ${notice}")
        endif()
        install(FILES "${notice}" DESTINATION c_spikes/licenses/${dependency} COMPONENT CSPPython)
    endforeach()
    if(WIN32)
        install(DIRECTORY "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/share/vcpkg-gfortran/licenses/"
            DESTINATION c_spikes/licenses/vcpkg-gfortran COMPONENT CSPPython)
    endif()
endif()
install(DIRECTORY licenses/gcc-runtime/ DESTINATION c_spikes/licenses/gcc-runtime COMPONENT CSPPython)
install(FILES "${kokkos_SOURCE_DIR}/LICENSE" DESTINATION c_spikes/licenses/kokkos COMPONENT CSPPython)
install(FILES src/c_spikes/oasis/PROVENANCE.md DESTINATION c_spikes/licenses/oasis COMPONENT CSPPython)
if(_pgas_build_gpu)
    find_package(CUDAToolkit REQUIRED)
    if(EXISTS "${CUDAToolkit_LIBRARY_ROOT}/licenses/cuda_cudart/LICENSE")
        install(DIRECTORY "${CUDAToolkit_LIBRARY_ROOT}/licenses/"
            DESTINATION c_spikes/licenses/cuda COMPONENT CSPPython)
    else()
        find_file(_csp_cuda_license NAMES EULA.txt
            HINTS "${CUDAToolkit_LIBRARY_ROOT}" NO_DEFAULT_PATH REQUIRED)
        install(FILES "${_csp_cuda_license}" DESTINATION c_spikes/licenses/cuda COMPONENT CSPPython)
    endif()
endif()

if(CSP_NATIVE_CORE_INSTALL)
    include(cmake/NativeCoreInstall.cmake)
endif()

# Isolated-process checked API validation only; normal public builds stay unchanged.
option(C_SPIKES_TEST_CHECKED_CPU "Build the isolated checked CPU API test surface." OFF)
if(C_SPIKES_TEST_CHECKED_CPU)
    if(_pgas_build_gpu)
        message(FATAL_ERROR "Checked API validation requires PGAS_BUILD_GPU=OFF")
    endif()
    foreach(_target pgas_obj_cpu pgas_bound_cpu)
        target_compile_definitions(${_target} PRIVATE C_SPIKES_CHECKED_CPU C_SPIKES_CHECKED_TESTING)
        target_compile_features(${_target} PRIVATE cxx_std_17)
        target_include_directories(${_target} PRIVATE src/c_spikes/pgas/include tests/native/g1e)
    endforeach()
endif()

option(C_SPIKES_TEST_SWEEP_CPU "Enable the isolated opt-in sweep preparation boundary." OFF)
if(C_SPIKES_TEST_SWEEP_CPU)
    if(_pgas_build_gpu OR NOT C_SPIKES_TEST_CHECKED_CPU)
        message(FATAL_ERROR "Sweep preparation validation requires CPU-only checked API validation")
    endif()
    foreach(_target pgas_obj_cpu pgas_bound_cpu)
        target_compile_definitions(${_target} PRIVATE C_SPIKES_CHECKED_SWEEP_CPU)
    endforeach()
endif()

option(C_SPIKES_TEST_SWEEP_RUN_CPU "Enable isolated opt-in single CPU sweep validation." OFF)
if(C_SPIKES_TEST_SWEEP_RUN_CPU)
    if(_pgas_build_gpu OR NOT C_SPIKES_TEST_SWEEP_CPU)
        message(FATAL_ERROR "Sweep execution validation requires CPU checked sweep preparation")
    endif()
    foreach(_target pgas_obj_cpu pgas_bound_cpu)
        target_compile_definitions(${_target} PRIVATE C_SPIKES_CHECKED_SWEEP_RUN_CPU)
    endforeach()
endif()

if(C_SPIKES_TEST_RESAMPLING)
    include(tests/native/standalone.cmake)
endif()
