# ML module CMake configuration
#
# Copyright (C) 2026 Qore Technologies, s.r.o.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

# Eigen is required (checked in top-level CMakeLists.txt)
# Try with version constraint first (Eigen 3.4.x), then without (Eigen 5.x)
find_package(Eigen3 3.4 QUIET NO_MODULE)
if (NOT Eigen3_FOUND)
    find_package(Eigen3 REQUIRED NO_MODULE)
endif()

# ONNX Runtime is optional
option(QORE_WITH_ONNXRUNTIME "Build the ml module with ONNX Runtime support when available" ON)
option(QORE_REQUIRE_ONNXRUNTIME "Fail configuration if ONNX Runtime support cannot be enabled" OFF)
set(HAVE_ONNXRUNTIME FALSE)
find_package(PkgConfig QUIET)
set(_onnxruntime_hints)
if (NOT QORE_REQUIRE_SYSTEM_DEPENDENCIES)
    list(APPEND _onnxruntime_hints /opt/onnxruntime)
endif()
if (QORE_WITH_ONNXRUNTIME AND PkgConfig_FOUND)
    # Developer installations may live in /opt; package builds use their declared search paths.
    set(_onnxruntime_pkg_config_path "$ENV{PKG_CONFIG_PATH}")
    if (_onnxruntime_hints)
        set(ENV{PKG_CONFIG_PATH} "$ENV{PKG_CONFIG_PATH}:/opt/onnxruntime/lib/pkgconfig")
    endif()
    pkg_check_modules(ONNXRUNTIME QUIET libonnxruntime)
    set(ENV{PKG_CONFIG_PATH} "${_onnxruntime_pkg_config_path}")
endif()
if (QORE_WITH_ONNXRUNTIME AND NOT ONNXRUNTIME_FOUND)
    find_library(ONNXRUNTIME_LIBRARY NAMES onnxruntime
                 HINTS ${_onnxruntime_hints} PATH_SUFFIXES lib)
    find_path(ONNXRUNTIME_INCLUDE_DIR onnxruntime_cxx_api.h
              HINTS ${_onnxruntime_hints} PATH_SUFFIXES include include/onnxruntime onnxruntime)
    if (ONNXRUNTIME_LIBRARY AND ONNXRUNTIME_INCLUDE_DIR)
        set(ONNXRUNTIME_FOUND TRUE)
        set(ONNXRUNTIME_LIBRARIES ${ONNXRUNTIME_LIBRARY})
        set(ONNXRUNTIME_INCLUDE_DIRS ${ONNXRUNTIME_INCLUDE_DIR})
    endif()
endif()
if (QORE_REQUIRE_ONNXRUNTIME AND (NOT QORE_WITH_ONNXRUNTIME OR NOT ONNXRUNTIME_FOUND))
    message(FATAL_ERROR "ONNX Runtime support is required; enable QORE_WITH_ONNXRUNTIME and install its development package")
endif()

# Start of hacks to simulate installed QoreConfig.cmake
if (NOT QORE_MODULES_DIR)
    set(QORE_MODULES_DIR ${MODULE_DIR})
endif()

if (NOT QORE_LIBRARY)
    set(QORE_LIBRARY libqore)
endif()

set(QORE_API_VERSION ${MODULE_API_MAJOR}.${MODULE_API_MINOR})

include(${CMAKE_SOURCE_DIR}/cmake/QoreMacros.cmake)
### end of hacks

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src/LBFGSpp)
include_directories(${CMAKE_CURRENT_BINARY_DIR})
include_directories(${CMAKE_BINARY_DIR}/include)
include_directories(${CMAKE_SOURCE_DIR}/include)

# QPP source files
set(ML_QPP_SRC
    src/QC_AbstractMLModel.qpp
    src/QC_AbstractMLEstimator.qpp
    src/QC_AbstractMLRegressor.qpp
    src/QC_AbstractMLClassifier.qpp
    src/QC_AbstractMLClusterer.qpp
    src/QC_AbstractMLAnomalyDetector.qpp
    src/QC_AbstractMLTransformer.qpp
    src/QC_AbstractMLTimeSeries.qpp
    src/QC_IsolationForest.qpp
    src/QC_DBSCAN.qpp
    src/QC_KMeans.qpp
    src/QC_HoltWinters.qpp
    src/QC_PCA.qpp
    src/QC_SeasonalDecomposition.qpp
    src/QC_LinearRegression.qpp
    src/QC_Ridge.qpp
    src/QC_Lasso.qpp
    src/QC_ElasticNet.qpp
    src/QC_LogisticRegression.qpp
    src/QC_LOF.qpp
    src/QC_KNN.qpp
    src/QC_GMM.qpp
    src/QC_Tensor.qpp
    src/QC_OnnxModel.qpp
    src/QC_StandardScaler.qpp
    src/QC_MinMaxScaler.qpp
    src/QC_Imputer.qpp
    src/QC_MLPipeline.qpp
    src/QC_CrossValidator.qpp
    src/QC_DecisionTree.qpp
    src/QC_RandomForest.qpp
    src/QC_GradientBoostedTrees.qpp
    src/QC_SVM.qpp
    src/QC_NaiveBayes.qpp
    src/QC_OneHotEncoder.qpp
    src/QC_LabelEncoder.qpp
    src/QC_VarianceThreshold.qpp
    src/QC_PolynomialFeatures.qpp
    src/QC_SelectKBest.qpp
    src/QC_RFE.qpp
    src/QC_ADWIN.qpp
    src/QC_PageHinkley.qpp
    src/QC_DDM.qpp
    src/QC_TextFeatures.qpp
    src/QC_DateTimeFeatures.qpp
    src/QC_SparseMatrix.qpp
    src/ql_ml.qpp
)

# C++ source files
set(ML_CPP_SRC
    src/ml-module.cpp
    src/ml_common.cpp
    src/ml_serialization.cpp
    src/IsolationForest.cpp
    src/DBSCAN.cpp
    src/KMeans.cpp
    src/HoltWinters.cpp
    src/PCA.cpp
    src/SeasonalDecomposition.cpp
    src/LinearRegression.cpp
    src/Ridge.cpp
    src/Lasso.cpp
    src/ElasticNet.cpp
    src/LogisticRegression.cpp
    src/LOF.cpp
    src/KNN.cpp
    src/GMM.cpp
    src/Tensor.cpp
    src/StandardScaler.cpp
    src/MinMaxScaler.cpp
    src/Imputer.cpp
    src/MLPipeline.cpp
    src/ml_metrics.cpp
    src/CrossValidator.cpp
    src/FlatTree.cpp
    src/DecisionTree.cpp
    src/RandomForest.cpp
    src/GradientBoostedTrees.cpp
    src/SVM.cpp
    src/NaiveBayes.cpp
    src/ml_stats.cpp
    src/OneHotEncoder.cpp
    src/LabelEncoder.cpp
    src/VarianceThreshold.cpp
    src/PolynomialFeatures.cpp
    src/SelectKBest.cpp
    src/RFE.cpp
    src/ml_tokenizer_bridge.cpp
    src/ADWIN.cpp
    src/PageHinkley.cpp
    src/DDM.cpp
    src/TextFeatures.cpp
    src/DateTimeFeatures.cpp
    src/ml_sparse.cpp
    src/SparseMatrix.cpp
)

# Conditional ONNX Runtime support
if (QORE_WITH_ONNXRUNTIME AND ONNXRUNTIME_FOUND)
    message(STATUS "ONNX Runtime found - building with ONNX model support")
    add_definitions(-DHAVE_ONNXRUNTIME)
    set(HAVE_ONNXRUNTIME TRUE)
    list(APPEND ML_CPP_SRC src/OnnxModel.cpp src/OnnxContentIdentity.cpp)
else()
    message(STATUS "Building without ONNX Runtime support - OnnxModel class will throw MISSING-FEATURE-ERROR")
endif()

# Optional CUDA runtime, used only to copy ONNX CUDA device-output buffers back to
# host memory.  Never required: CPU-only (and ROCm) builds simply cannot
# materialize CUDA device outputs and report that clearly at runtime.
set(HAVE_CUDART FALSE)
if (HAVE_ONNXRUNTIME)
    find_package(CUDAToolkit QUIET)
    if (CUDAToolkit_FOUND AND TARGET CUDA::cudart)
        message(STATUS "CUDA runtime found (${CUDAToolkit_VERSION}) - ONNX device-output copy-to-host enabled")
        set(HAVE_CUDART TRUE)
    else()
        message(STATUS "CUDA runtime not found - ONNX CUDA device outputs will be unavailable")
    endif()
endif()

# Optional Metal framework on Apple Silicon / macOS, used to allocate UMA
# (Unified Memory Architecture) device buffers via MTLBuffer with
# MTLStorageModeShared.  On UMA, "device" and "host" memory are the same
# physical bytes -- the copy-to-host callback is a no-op, transfer counters
# stay 0, and pinnedHost() is moot.  Never required: non-Apple builds and
# CoreML-only macOS builds simply lack the upload path and report it clearly.
set(HAVE_METAL FALSE)
if (APPLE AND HAVE_ONNXRUNTIME)
    find_library(METAL_FRAMEWORK Metal)
    find_library(FOUNDATION_FRAMEWORK Foundation)
    if (METAL_FRAMEWORK AND FOUNDATION_FRAMEWORK)
        message(STATUS "Metal framework found - macOS Metal/UMA device buffers enabled")
        set(HAVE_METAL TRUE)
        list(APPEND ML_CPP_SRC src/Tensor_Metal.mm)
    else()
        message(STATUS "Metal framework not found - macOS Metal/UMA device buffers disabled")
    endif()
endif()

set(QORE_DOX_ML_TMPL_SRC
    docs/mainpage.dox.tmpl
)

# Process QPP files
qore_wrap_qpp_value(ML_QPP_SOURCES DOXLIST _dox_src ${ML_QPP_SRC})
add_custom_target(ML_QPP_GENERATED_FILES DEPENDS qpp ${ML_QPP_SOURCES})

# Create the module library
set(ml_module_name "ml")

add_library(${ml_module_name} MODULE ${ML_CPP_SRC} ${ML_QPP_SOURCES})
target_link_libraries(${ml_module_name} Eigen3::Eigen)
if (HAVE_ONNXRUNTIME)
    target_include_directories(${ml_module_name} PRIVATE ${ONNXRUNTIME_INCLUDE_DIRS})
    if (ONNXRUNTIME_LIBRARY_DIRS)
        target_link_directories(${ml_module_name} PRIVATE ${ONNXRUNTIME_LIBRARY_DIRS})
    endif()
    target_link_libraries(${ml_module_name} ${ONNXRUNTIME_LIBRARIES})
    # OpenSSL provides the SHA-256 digests used for ONNX loaded-content identity
    target_link_libraries(${ml_module_name} ${OPENSSL_LIBRARIES})
    target_include_directories(${ml_module_name} PRIVATE ${OPENSSL_INCLUDE_DIR})
    if (HAVE_CUDART)
        target_compile_definitions(${ml_module_name} PRIVATE HAVE_CUDART)
        target_link_libraries(${ml_module_name} CUDA::cudart)
    endif()
    if (HAVE_METAL)
        target_compile_definitions(${ml_module_name} PRIVATE HAVE_METAL)
        target_link_libraries(${ml_module_name} ${METAL_FRAMEWORK} ${FOUNDATION_FRAMEWORK})
        set_source_files_properties(src/Tensor_Metal.mm PROPERTIES COMPILE_FLAGS "-fobjc-arc")
    endif()
endif()
add_dependencies(${ml_module_name} libqore ML_QPP_GENERATED_FILES)

set(MODULE_DOX_INPUT ${CMAKE_BINARY_DIR}/modules/ml/mainpage.dox ${_dox_src})
qore_binary_module_qore(${ml_module_name} "${VERSION}" "/${VERSION}")

if (DOXYGEN_FOUND)
    qore_wrap_dox(QORE_DOX_ML_SRC ${QORE_DOX_ML_TMPL_SRC})
    add_custom_target(QORE_ML_MOD_DOX_FILES DEPENDS ${QORE_DOX_ML_SRC})
    add_dependencies(docs-ml QORE_ML_MOD_DOX_FILES)
endif()
