# CMakeLists.txt — AutoSpectral kernels: the Optimization kernel
# (_autospectral_opt_kernel, pybind11 + Armadillo) and the M2p noise-model
# GLS kernel (_gls_m2p_kernel, pybind11 + BLAS dgemm, no Armadillo).
#
# Prerequisites (macOS, local + CI):
#   brew install armadillo libomp cmake
#   pip install pybind11
# Prerequisites (Windows, CI): Armadillo + OpenBLAS via vcpkg (static, see
#   the BLA_STATIC block below), pybind11 via pip — see build.yml for the
#   exact CI step.
# Linux is not an active CI target today (see build.yml matrix — the ubuntu
# runners are commented out) — no apt-based prerequisites have been set up
# or verified for this extension yet.
#
# Usage: run build_autospectral_opt_kernel.py rather than invoking cmake
# directly — it wires up Python3_EXECUTABLE and the OpenMP option for you.

cmake_minimum_required(VERSION 3.18)
project(autospectral_opt_kernel LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

if(NOT CMAKE_BUILD_TYPE)
  set(CMAKE_BUILD_TYPE Release)
endif()
if(MSVC)
  set(CMAKE_CXX_FLAGS_RELEASE "/O2 /Ob2 /DNDEBUG")
else()
  set(CMAKE_CXX_FLAGS_RELEASE "-O3")
endif()

find_package(Python3 COMPONENTS Interpreter Development REQUIRED)

execute_process(
  COMMAND "${Python3_EXECUTABLE}" -m pybind11 --cmakedir
  OUTPUT_VARIABLE pybind11_DIR
  OUTPUT_STRIP_TRAILING_WHITESPACE
  RESULT_VARIABLE _pybind11_dir_result
)
if(NOT _pybind11_dir_result EQUAL 0)
  message(FATAL_ERROR
    "Could not run '${Python3_EXECUTABLE} -m pybind11 --cmakedir' — "
    "is pybind11 installed for this interpreter? "
    "Try, from the repository root: ${Python3_EXECUTABLE} -m pip install -r requirements.txt")
endif()

# Static OpenBLAS on Windows/Linux — single binary, nothing extra to track through the PyInstaller
# spec or the codesign/notarization pass. macOS is unaffected: there the
# Optimization kernel uses Armadillo header-only with Apple's Accelerate
# framework (below), so this flag has no effect.
if(NOT APPLE)
  set(BLA_STATIC ON)
endif()

find_package(pybind11 REQUIRED)
find_package(Armadillo REQUIRED)

pybind11_add_module(_autospectral_opt_kernel
  autospectral_opt_pybind.cpp
  core_joint_unmix.cpp
  af_negative_term.cpp
)

target_include_directories(_autospectral_opt_kernel PRIVATE ${ARMADILLO_INCLUDE_DIRS})
if(APPLE)
  # Header-only Armadillo calling Accelerate's BLAS and LAPACK directly. The
  # kernel then links no libarmadillo (Homebrew's pulls in OpenBLAS, ARPACK
  # and the gfortran runtime, none of which ship with the app), only system
  # frameworks and libomp. The kernel uses dense solvers only, so ARPACK,
  # SuperLU and HDF5 are switched off.
  target_compile_definitions(_autospectral_opt_kernel PRIVATE
    ARMA_DONT_USE_WRAPPER
    ARMA_DONT_USE_ARPACK
    ARMA_DONT_USE_SUPERLU
    ARMA_DONT_USE_HDF5
  )
  target_link_libraries(_autospectral_opt_kernel PRIVATE "-framework Accelerate")
else()
  target_link_libraries(_autospectral_opt_kernel PRIVATE ${ARMADILLO_LIBRARIES})
endif()

# BLAS: Accelerate on macOS, the static OpenBLAS (BLA_STATIC above) on Windows,
# the shared system BLAS on Linux (distribution static archives are not built
# with -fPIC). The kernel calls dgemm_ with 32-bit integers.
if(UNIX AND NOT APPLE)
  set(BLA_STATIC OFF)
endif()
find_package(BLAS REQUIRED)
pybind11_add_module(_gls_m2p_kernel gls_m2p_kernel.cpp)
target_link_libraries(_gls_m2p_kernel PRIVATE ${BLAS_LIBRARIES})

set(HONEYCHROME_KERNELS _autospectral_opt_kernel _gls_m2p_kernel)

option(HONEYCHROME_OPENMP "Enable OpenMP in the AutoSpectral kernels" ON)

if(HONEYCHROME_OPENMP)
  if(APPLE)
    # libomp under $HONEYCHROME_LIBOMP_PREFIX when set, otherwise Homebrew's;
    # same approach as build_som_kernel.py.
    if(NOT "$ENV{HONEYCHROME_LIBOMP_PREFIX}" STREQUAL "")
      set(LIBOMP_PREFIX "$ENV{HONEYCHROME_LIBOMP_PREFIX}")
      set(_libomp_prefix_result 0)
    else()
      execute_process(
        COMMAND brew --prefix libomp
        OUTPUT_VARIABLE LIBOMP_PREFIX
        OUTPUT_STRIP_TRAILING_WHITESPACE
        ERROR_QUIET
        RESULT_VARIABLE _libomp_prefix_result
      )
    endif()
    if(_libomp_prefix_result EQUAL 0 AND LIBOMP_PREFIX)
      foreach(kernel IN LISTS HONEYCHROME_KERNELS)
        target_compile_options(${kernel} PRIVATE -Xpreprocessor -fopenmp -I${LIBOMP_PREFIX}/include)
        target_link_directories(${kernel} PRIVATE ${LIBOMP_PREFIX}/lib)
        target_link_libraries(${kernel} PRIVATE omp)
        # Finds a libomp whose install name is @rpath/libomp.dylib (conda-forge's)
        target_link_options(${kernel} PRIVATE "LINKER:-rpath,${LIBOMP_PREFIX}/lib")
      endforeach()
      message(STATUS "AutoSpectral kernels: macOS OpenMP via libomp at ${LIBOMP_PREFIX}")
    else()
      message(WARNING
        "HONEYCHROME_OPENMP=ON but 'brew --prefix libomp' failed — "
        "building single-threaded. Run: brew install libomp")
      set(HONEYCHROME_OPENMP OFF)
    endif()
  else()
    if(MSVC)
        # MSVC's /openmp does not accept '#pragma omp simd' (error C7660);
        # /openmp:experimental does, and is a superset of /openmp.
        foreach(kernel IN LISTS HONEYCHROME_KERNELS)
          target_compile_options(${kernel} PRIVATE /openmp:experimental)
          target_link_options(${kernel} PRIVATE /openmp:experimental)
        endforeach()
        message(STATUS "AutoSpectral kernels: MSVC OpenMP via /openmp:experimental")
    else()
        find_package(OpenMP REQUIRED)
        foreach(kernel IN LISTS HONEYCHROME_KERNELS)
          target_link_libraries(${kernel} PRIVATE OpenMP::OpenMP_CXX)
        endforeach()
    endif()
  endif()
else()
  message(STATUS "AutoSpectral kernels: building single-threaded (HONEYCHROME_OPENMP=OFF).")
endif()
