# 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/.
cmake_minimum_required(VERSION 3.30)
project(lunopt
    VERSION 0.16.0
    DESCRIPTION "LUNOPT, the Lightweight Unified Nonlinear OPTimiser"
    LANGUAGES CXX)

option(LUNOPT_BUILD_TESTS "Build LUNOPT's tests" ${PROJECT_IS_TOP_LEVEL})
option(LUNOPT_FETCH_EIGEN "Fetch Eigen 5.0.1 where no Eigen3::Eigen target exists" ON)
option(LUNOPT_WERROR "Warnings as errors in LUNOPT's own targets" OFF)
set(LUNOPT_SANITIZE "" CACHE STRING "Sanitizers for the tests, e.g. address,undefined")
option(LUNOPT_BUILD_BENCH "Build the benchmarks' driver (bench/, docs/benchmarks.md; never in a package)" OFF)
option(LUNOPT_PYTHON "Build the Python bindings (needs Python 3.12+ with nanobind)" OFF)

include(FetchContent)

# Eigen: the including project's Eigen3::Eigen target where it has one, else Eigen 5.0.1 (MPL-2.0) pinned by its hash,
# else an installed Eigen 5. Header-only: Eigen's own CMake project is not configured. The fetched one is the target
# lunopt_eigen, not named Eigen3::Eigen, so that the installed package's Eigen3::Eigen means the user's Eigen.
set(_lunopt_eigen Eigen3::Eigen)
if(NOT TARGET Eigen3::Eigen)
    if(LUNOPT_FETCH_EIGEN)
        FetchContent_Declare(Eigen
            URL      https://gitlab.com/libeigen/eigen/-/archive/5.0.1/eigen-5.0.1.tar.gz
            URL_HASH SHA256=e9c326dc8c05cd1e044c71f30f1b2e34a6161a3b6ecf445d56b53ff1669e3dec
            DOWNLOAD_EXTRACT_TIMESTAMP ON
            SOURCE_SUBDIR do-not-configure)
        FetchContent_MakeAvailable(Eigen)
        add_library(lunopt_eigen INTERFACE)
        target_include_directories(lunopt_eigen SYSTEM INTERFACE "${eigen_SOURCE_DIR}")
        set(_lunopt_eigen lunopt_eigen)
    else()
        find_package(Eigen3 5 REQUIRED CONFIG)
    endif()
endif()

# The library: header-only, C++23.
include(GNUInstallDirs)
add_library(lunopt INTERFACE)
add_library(lunopt::lunopt ALIAS lunopt)
target_include_directories(lunopt INTERFACE "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>"
                                            "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>")
target_compile_features(lunopt INTERFACE cxx_std_23)
# Installed, it asks for an installed Eigen 5 (lunoptConfig.cmake finds it), whichever Eigen built it here.
target_link_libraries(lunopt INTERFACE "$<BUILD_INTERFACE:${_lunopt_eigen}>" "$<INSTALL_INTERFACE:Eigen3::Eigen>")

# cmake --install: the headers and lunoptConfig.cmake, for find_package( lunopt ) and the target lunopt::lunopt (not
# from a Python wheel's build, which installs the module alone).
option(LUNOPT_INSTALL "Install the headers and the CMake package" ${PROJECT_IS_TOP_LEVEL})
if(LUNOPT_INSTALL AND NOT SKBUILD)
    include(CMakePackageConfigHelpers)
    set(_lunopt_cmake_dir "${CMAKE_INSTALL_DATADIR}/cmake/lunopt") # header-only: architecture-independent
    install(TARGETS lunopt EXPORT lunoptTargets)
    install(DIRECTORY include/lunopt DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
    install(EXPORT lunoptTargets NAMESPACE lunopt:: DESTINATION "${_lunopt_cmake_dir}")
    configure_package_config_file(cmake/lunoptConfig.cmake.in "${PROJECT_BINARY_DIR}/lunoptConfig.cmake"
                                  INSTALL_DESTINATION "${_lunopt_cmake_dir}")
    write_basic_package_version_file("${PROJECT_BINARY_DIR}/lunoptConfigVersion.cmake"
                                     COMPATIBILITY SameMinorVersion ARCH_INDEPENDENT)
    install(FILES "${PROJECT_BINARY_DIR}/lunoptConfig.cmake" "${PROJECT_BINARY_DIR}/lunoptConfigVersion.cmake"
            DESTINATION "${_lunopt_cmake_dir}")
endif()

if(LUNOPT_BUILD_TESTS)
    enable_testing()
    set(CMAKE_CXX_STANDARD 23)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    set(CMAKE_CXX_EXTENSIONS OFF)
    set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
    # No FMA contraction, no fast-math: the tests' figures the same on every machine.
    add_compile_options(-ffp-contract=off)
    if(LUNOPT_SANITIZE)
        add_compile_options(-fsanitize=${LUNOPT_SANITIZE} -fno-omit-frame-pointer -fno-sanitize-recover=undefined)
        add_link_options(-fsanitize=${LUNOPT_SANITIZE})
        add_compile_definitions(_GLIBCXX_ASSERTIONS)
    endif()

    FetchContent_Declare(Catch2
        URL      https://github.com/catchorg/Catch2/archive/refs/tags/v3.16.1.tar.gz
        URL_HASH SHA256=d16bd1b8b2364918bd472cb216394acb93bde6784890df0d91bccfb3f28d777d
        DOWNLOAD_EXTRACT_TIMESTAMP ON
        SYSTEM)
    FetchContent_MakeAvailable(Catch2)
    list(APPEND CMAKE_MODULE_PATH "${catch2_SOURCE_DIR}/extras")
    include(Catch)

    set(_lunopt_warnings -Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wshadow -Wdouble-promotion -Wundef)
    if(LUNOPT_WERROR)
        list(APPEND _lunopt_warnings -Werror)
    endif()

    # Each header compiles on its own.
    file(GLOB _lunopt_headers CONFIGURE_DEPENDS "${PROJECT_SOURCE_DIR}/include/lunopt/*.hpp")
    set(_lunopt_header_tus "")
    foreach(_h IN LISTS _lunopt_headers)
        get_filename_component(_name "${_h}" NAME_WE)
        set(_tu "${PROJECT_BINARY_DIR}/headers/${_name}.cpp")
        file(CONFIGURE OUTPUT "${_tu}" CONTENT "#include \"lunopt/${_name}.hpp\"\n")
        list(APPEND _lunopt_header_tus "${_tu}")
    endforeach()
    add_library(lunopt_headers OBJECT ${_lunopt_header_tus})
    target_link_libraries(lunopt_headers PRIVATE lunopt::lunopt)
    target_compile_options(lunopt_headers PRIVATE ${_lunopt_warnings})

    add_executable(lunopt_tests tests/test_ad.cpp tests/test_dense.cpp tests/test_diagnosis.cpp tests/test_sqp.cpp)
    target_link_libraries(lunopt_tests PRIVATE lunopt::lunopt Catch2::Catch2WithMain)
    target_compile_options(lunopt_tests PRIVATE ${_lunopt_warnings})
    catch_discover_tests(lunopt_tests TEST_PREFIX "lunopt: " DISCOVERY_MODE PRE_TEST)

    # The README's example.
    add_executable(lunopt_readme examples/readme.cpp)
    target_link_libraries(lunopt_readme PRIVATE lunopt::lunopt)
    target_compile_options(lunopt_readme PRIVATE ${_lunopt_warnings})
    add_test(NAME "lunopt: the README's example" COMMAND lunopt_readme)
endif()

if(LUNOPT_PYTHON)
    add_subdirectory(python)
endif()

if(LUNOPT_BUILD_BENCH)
    add_subdirectory(bench)
endif()
