cmake_minimum_required(VERSION 3.24)
project(pixie_py LANGUAGES CXX)

find_package(Python 3.10 REQUIRED COMPONENTS Interpreter Development.Module)
find_package(nanobind CONFIG REQUIRED)
include(FetchContent)

set(PIXIE_SOURCE_DIR "$ENV{PIXIE_SOURCE_DIR}" CACHE PATH "Optional local Pixie checkout")
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/pyproject.toml" version_line REGEX "^version = ")
string(REGEX REPLACE "^version = \"([^\"]+)\"$" "\\1" pixie_version "${version_line}")
# Consume public headers without importing the core's native CPU flags or tests.
FetchContent_Declare(pixie
  GIT_REPOSITORY https://github.com/Malkovsky/pixie.git
  GIT_TAG v${pixie_version}
  GIT_SHALLOW TRUE
  GIT_SUBMODULES ""
  SOURCE_SUBDIR pixie-py-headers-only)
if(PIXIE_SOURCE_DIR)
  set(FETCHCONTENT_SOURCE_DIR_PIXIE "${PIXIE_SOURCE_DIR}")
endif()
FetchContent_MakeAvailable(pixie)
if(NOT EXISTS "${pixie_SOURCE_DIR}/include/pixie/tree/tree_part.h")
  message(FATAL_ERROR "The selected Pixie checkout is missing include/pixie/tree/tree_part.h. Use a checkout with the traversal API.")
endif()

execute_process(COMMAND git rev-parse HEAD WORKING_DIRECTORY "${pixie_SOURCE_DIR}"
    OUTPUT_VARIABLE PIXIE_BUILD_REVISION OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
if(PIXIE_SOURCE_DIR)
  execute_process(COMMAND git diff --quiet -- include WORKING_DIRECTORY "${pixie_SOURCE_DIR}"
    RESULT_VARIABLE PIXIE_CORE_DIRTY)
  if(PIXIE_CORE_DIRTY)
    string(APPEND PIXIE_BUILD_REVISION "-dirty")
  endif()
endif()
function(add_pixie_bindings target)
  nanobind_add_module(${target} NB_STATIC src/bindings.cpp src/rmq_bindings.cpp src/tree_bindings.cpp)
  target_compile_features(${target} PRIVATE cxx_std_20)
  target_include_directories(${target} PRIVATE "${pixie_SOURCE_DIR}/include")
  target_compile_definitions(${target} PRIVATE PIXIE_MODULE=${target}
    PIXIE_PY_CORE_REVISION="${PIXIE_BUILD_REVISION}")
  install(TARGETS ${target} LIBRARY DESTINATION pixie)
endfunction()

option(PIXIE_PY_DISPATCH "Bundle Linux x86-64 backends for import-time selection" OFF)
if(PIXIE_PY_DISPATCH)
  if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux" OR NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$")
    message(FATAL_ERROR "PIXIE_PY_DISPATCH requires Linux x86-64")
  endif()
  include("${pixie_SOURCE_DIR}/cmake/PixieCpuProfiles.cmake")
  foreach(profile IN ITEMS sse2 avx2 x86-64-v3 avx512-full)
    string(REPLACE "-" "_" suffix "${profile}")
    set(target "_core_${suffix}")
    add_pixie_bindings(${target})
    pixie_cpu_profile_flags(flags "${profile}")
    target_compile_options(${target} PRIVATE ${flags})
  endforeach()
  nanobind_add_module(_cpu NB_STATIC src/cpu.cpp)
  target_compile_options(_cpu PRIVATE -march=x86-64)
  install(TARGETS _cpu LIBRARY DESTINATION pixie)
  install(FILES src/cpu_dispatch.py DESTINATION pixie RENAME _core.py)
else()
  add_pixie_bindings(_core)
endif()
