cmake_minimum_required(VERSION 3.16)
project(ngtstore LANGUAGES CXX)

find_package(SQLite3 REQUIRED)

add_library(ngtstore
  src/filter.cpp
  src/filter_bitmap.cpp
  src/index_options_json.cpp
  src/sqlite_metadata_store.cpp
)

target_include_directories(ngtstore PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_compile_features(ngtstore PUBLIC cxx_std_17)
target_link_libraries(ngtstore PUBLIC SQLite::SQLite3)
# Needed when these static libraries are linked into the pybind11 module.
set_target_properties(ngtstore PROPERTIES POSITION_INDEPENDENT_CODE ON)

option(NGTSTORE_WITH_NGT "Build the NGT connection layer" OFF)
option(NGTSTORE_BUILD_TESTS "Build NGT-store tests" ON)
option(NGTSTORE_BUILD_PYTHON "Build pybind11 Python bindings" OFF)
option(NGTSTORE_BUILD_BENCH "Build the filter benchmark harness (bench/)" OFF)
# Python extension variant for fat wheels: "single" (default) builds the plain
# _ngtstore module; "base" and "avx2" build _ngtstore_base / _ngtstore_avx2
# with NGT compiled for the corresponding instruction set. The x86_64 release
# wheel bundles base and avx2 and picks one at import time.
set(NGTSTORE_SIMD_VARIANT "single" CACHE STRING
  "Python extension variant: single, base, avx2, or avx512")
string(TOLOWER "${NGTSTORE_SIMD_VARIANT}" NGTSTORE_SIMD_VARIANT)
if(NOT NGTSTORE_SIMD_VARIANT MATCHES "^(single|base|avx2|avx512)$")
  message(FATAL_ERROR
    "NGTSTORE_SIMD_VARIANT must be one of single, base, avx2 (got "
    "'${NGTSTORE_SIMD_VARIANT}')")
endif()
if(NGTSTORE_SIMD_VARIANT STREQUAL "single")
  set(NGTSTORE_PYTHON_MODULE "_ngtstore")
else()
  set(NGTSTORE_PYTHON_MODULE "_ngtstore_${NGTSTORE_SIMD_VARIANT}")
endif()

if(NGTSTORE_BUILD_PYTHON AND NOT NGTSTORE_WITH_NGT)
  message(FATAL_ERROR "NGTSTORE_BUILD_PYTHON requires NGTSTORE_WITH_NGT=ON")
endif()

if(NGTSTORE_WITH_NGT)
  if(NGT_ROOT)
    list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
    find_package(NGT REQUIRED)
  else()
    # Vendored NGT: build the third_party/ngt submodule into this build and
    # link it statically, which keeps the Python extension self-contained
    # (no system NGT shared library at run time). The generated defines.h
    # enables NGT_GRAPH_READ_ONLY_GRAPH unconditionally and leaves
    # NGT_SHARED_MEMORY_ALLOCATOR off, so filtered search works out of the
    # box. Set NGT_ROOT to use an installed NGT instead.
    set(NGTSTORE_VENDORED_NGT "${CMAKE_CURRENT_SOURCE_DIR}/third_party/ngt")
    if(NOT EXISTS "${NGTSTORE_VENDORED_NGT}/CMakeLists.txt")
      message(FATAL_ERROR
        "third_party/ngt is missing. Either set NGT_ROOT to an installed NGT "
        "or fetch the submodule: git submodule update --init --recursive")
    endif()
    # Variants only change how the vendored NGT is compiled; an installed NGT
    # (NGT_ROOT) is used as-is. The flags mirror what NGT's own CMake applies
    # to its sources per variant. x86 only: NGT adds -march=haswell without an
    # architecture check of its own, and on aarch64 the defines.h neutralizes
    # the AVX macros and NGT_MARCH_NATIVE_DISABLED (set by the wheel CI)
    # governs the flags instead.
    if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|i.86)$")
      if(NGTSTORE_SIMD_VARIANT STREQUAL "base")
        set(NGT_AVX_DISABLED ON)
        set(NGTSTORE_NGT_ISA_FLAGS -march=x86-64)
      elseif(NGTSTORE_SIMD_VARIANT STREQUAL "avx2")
        set(NGT_AVX2 ON)
        set(NGTSTORE_NGT_ISA_FLAGS -march=haswell)
      elseif(NGTSTORE_SIMD_VARIANT STREQUAL "avx512")
        # NGT upstream has no AVX-512 option. Keep NGT's own option set (the
        # same as the avx2 variant: NGT's sources compile with -O3 -ffast-math
        # and use its AVX2 intrinsics paths) and retarget the instruction set
        # to the portable x86-64-v4 baseline (AVX-512F/BW/CD/DQ/VL). The flag
        # is appended to NGT's targets below, after the directory-scope
        # -march=haswell that NGT adds; the last -march wins with GCC. NGT's
        # remaining scalar loops then auto-vectorize with AVX-512. v4 needs
        # GCC 11+ / Clang 12+, which every supported toolchain provides.
        set(NGT_AVX2 ON)
        set(NGTSTORE_NGT_ISA_FLAGS -march=x86-64-v4)
        set(NGTSTORE_APPEND_NGT_ISA_FLAGS -march=x86-64-v4)
      else()
        set(NGTSTORE_NGT_ISA_FLAGS -march=native)
      endif()
    endif()
    # EXCLUDE_FROM_ALL: the extension statically links ngtstatic, so NGT's
    # shared library, commands, and samples never need to build for our
    # targets. Skipping them shortens the wheel build and avoids exercising
    # NGT's hardcoded -llapack/-lblas link of libngt.so; the extension itself
    # links whatever find_package(BLAS) below resolves.
    add_subdirectory("${NGTSTORE_VENDORED_NGT}" "${CMAKE_BINARY_DIR}/ngt" EXCLUDE_FROM_ALL)
    unset(NGT_AVX_DISABLED)
    unset(NGT_AVX2)
    if(NGTSTORE_APPEND_NGT_ISA_FLAGS)
      foreach(NGTSTORE_NGT_TARGET IN ITEMS ngt ngtstatic)
        if(TARGET ${NGTSTORE_NGT_TARGET})
          set_property(TARGET ${NGTSTORE_NGT_TARGET} APPEND PROPERTY
            COMPILE_OPTIONS ${NGTSTORE_APPEND_NGT_ISA_FLAGS})
        endif()
      endforeach()
    endif()
    unset(NGTSTORE_APPEND_NGT_ISA_FLAGS)
    # NGT keeps the include directories on its own directory scope, and its
    # static target only carries OpenMP on AppleClang. Wrap what the
    # FindNGT.cmake imported target provides into an interface target.
    find_package(OpenMP REQUIRED)
    add_library(ngtstore_vendored_ngt INTERFACE)
    target_include_directories(ngtstore_vendored_ngt INTERFACE
      "${NGTSTORE_VENDORED_NGT}/lib"
      "${CMAKE_BINARY_DIR}/ngt/lib")
    target_link_libraries(ngtstore_vendored_ngt INTERFACE ngtstatic OpenMP::OpenMP_CXX)
    add_library(NGT::NGT ALIAS ngtstore_vendored_ngt)
    # Static linking leaves no library directory to embed in an RPATH.
    set(NGT_LIBRARY_DIR "")
  endif()
  # NGT's QBG optimizer uses BLAS from inline headers (sgemv_).
  find_package(BLAS REQUIRED)

  add_library(ngtstore_ngt
    src/ngt_index.cpp
    src/ngt_store.cpp
  )
  target_compile_features(ngtstore_ngt PUBLIC cxx_std_17)
  target_link_libraries(ngtstore_ngt PUBLIC ngtstore PRIVATE NGT::NGT ${BLAS_LIBRARIES})
  set_target_properties(ngtstore_ngt PROPERTIES POSITION_INDEPENDENT_CODE ON)
  # The vendored NGT bakes its ISA option into the generated defines.h and
  # compiles its own sources with a matching -march. Every TU that includes
  # NGT headers must see the same instruction set, or Quantizer.h activates
  # its AVX2 paths (from defines.h) in a TU compiled without -march=haswell
  # and fails with undeclared intrinsics. x86 only: the aarch64 defines.h
  # neutralizes the AVX macros itself. Deliberately NOT adding -ffast-math:
  # NGT's own builds use it, but with it our TU's inlined normalization
  # changes results (e.g. an identical-point distance of 0.0 drifts to 3.4e-4
  # on x86) and breaks the distance-type precision tests.
  if(NGTSTORE_NGT_ISA_FLAGS AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|i.86)$")
    target_compile_options(ngtstore_ngt PRIVATE ${NGTSTORE_NGT_ISA_FLAGS})
  endif()

  if(NGTSTORE_BUILD_BENCH)
    add_executable(ngtstore_filter_bench bench/filter_bench.cpp)
    target_compile_features(ngtstore_filter_bench PRIVATE cxx_std_17)
    target_link_libraries(ngtstore_filter_bench PRIVATE ngtstore_ngt)
    set_target_properties(ngtstore_filter_bench PROPERTIES
      BUILD_RPATH "${NGT_LIBRARY_DIR}")
  endif()
endif()

if(NGTSTORE_BUILD_PYTHON)
  # pybind11 is a build-time dependency only. With the vendored NGT the
  # extension links ngtstatic and is self-contained; with NGT_ROOT it still
  # requires the system NGT shared library at run time.
  find_package(Python COMPONENTS Interpreter Development.Module REQUIRED)
  # Locate the pybind11 that belongs to the selected Python when the caller did
  # not provide pybind11_DIR.
  if(NOT pybind11_DIR)
    execute_process(
      COMMAND ${Python_EXECUTABLE} -m pybind11 --cmakedir
      OUTPUT_VARIABLE NGTSTORE_PYBIND11_DIR
      OUTPUT_STRIP_TRAILING_WHITESPACE
      ERROR_QUIET)
    if(NGTSTORE_PYBIND11_DIR)
      set(pybind11_DIR "${NGTSTORE_PYBIND11_DIR}")
    endif()
  endif()
  find_package(pybind11 CONFIG REQUIRED)

  set(NGTSTORE_PYTHON_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/python/ngtstore")

  pybind11_add_module(${NGTSTORE_PYTHON_MODULE} MODULE src/python_bindings.cpp)
  # The module init function must match the file name; the source uses the
  # two-level NGTSTORE_PYBIND11_MODULE wrapper so this -D reaches it expanded.
  target_compile_definitions(${NGTSTORE_PYTHON_MODULE} PRIVATE
    NGTSTORE_MODULE_NAME=${NGTSTORE_PYTHON_MODULE})
  target_link_libraries(${NGTSTORE_PYTHON_MODULE} PRIVATE ngtstore_ngt)
  set_target_properties(${NGTSTORE_PYTHON_MODULE} PROPERTIES
    LIBRARY_OUTPUT_DIRECTORY "${NGTSTORE_PYTHON_OUTPUT_DIR}"
    BUILD_RPATH "${NGT_LIBRARY_DIR}")

  # The pure-Python facade sits next to the extension in the build tree so that
  # PYTHONPATH=<build>/python is enough to import ngtstore. A separate target
  # keeps the copies in sync even when the extension itself is up to date.
  add_custom_target(ngtstore_python_facade ALL
    COMMAND ${CMAKE_COMMAND} -E make_directory "${NGTSTORE_PYTHON_OUTPUT_DIR}"
    COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${CMAKE_CURRENT_SOURCE_DIR}/python/ngtstore/__init__.py"
            "${NGTSTORE_PYTHON_OUTPUT_DIR}/__init__.py"
    COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${CMAKE_CURRENT_SOURCE_DIR}/python/ngtstore/llama_index.py"
            "${NGTSTORE_PYTHON_OUTPUT_DIR}/llama_index.py"
    COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${CMAKE_CURRENT_SOURCE_DIR}/python/ngtstore/llama_index_store.py"
            "${NGTSTORE_PYTHON_OUTPUT_DIR}/llama_index_store.py"
    VERBATIM)
  add_dependencies(ngtstore_python_facade ${NGTSTORE_PYTHON_MODULE})

  # scikit-build-core assembles the wheel with cmake --install, restricted to
  # this component ([tool.scikit-build] install.components), so the NGT
  # vendored build's own install rules stay out of the wheel. The extension
  # goes into the package directory next to the facade copied into it by
  # [tool.scikit-build] wheel.packages.
  install(TARGETS ${NGTSTORE_PYTHON_MODULE} LIBRARY DESTINATION ngtstore
    COMPONENT ngtstore)
endif()

if(NGTSTORE_BUILD_TESTS)
  enable_testing()

  add_executable(ngtstore_tests tests/sqlite_metadata_store_test.cpp)
  target_link_libraries(ngtstore_tests PRIVATE ngtstore)
  add_test(NAME ngtstore_tests COMMAND ngtstore_tests)
  set_tests_properties(ngtstore_tests PROPERTIES
    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})

  if(NGTSTORE_WITH_NGT)
    add_executable(ngtstore_ngt_tests tests/ngt_store_test.cpp)
    target_link_libraries(ngtstore_ngt_tests PRIVATE ngtstore_ngt)
    add_test(NAME ngtstore_ngt_tests COMMAND ngtstore_ngt_tests)
    set_tests_properties(ngtstore_ngt_tests PROPERTIES
      WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
    set_target_properties(ngtstore_ngt_tests PROPERTIES
      BUILD_RPATH "${NGT_LIBRARY_DIR}")
  endif()

  if(NGTSTORE_BUILD_PYTHON)
    add_test(NAME ngtstore_python_tests
      COMMAND ${Python_EXECUTABLE} -m unittest discover
              -s ${CMAKE_CURRENT_SOURCE_DIR}/tests/python -v)
    set_tests_properties(ngtstore_python_tests PROPERTIES
      ENVIRONMENT "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/python"
      WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
  endif()
endif()
