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")
set(PIXIE_REVISION be9f30dcc1b823fadf17c3fc67ee7cd425e98ee8)
# 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 ${PIXIE_REVISION}
  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/decoded_tree.h")
  message(FATAL_ERROR "The selected Pixie checkout is missing include/pixie/tree/decoded_tree.h. Use a checkout with the traversal API.")
endif()

nanobind_add_module(_core NB_STATIC src/bindings.cpp src/rmq_bindings.cpp)
target_compile_features(_core PRIVATE cxx_std_20)
target_include_directories(_core PRIVATE ${pixie_SOURCE_DIR}/include)
set(PIXIE_BUILD_REVISION "${PIXIE_REVISION}")
if(PIXIE_SOURCE_DIR)
  execute_process(COMMAND git rev-parse HEAD WORKING_DIRECTORY "${pixie_SOURCE_DIR}"
    OUTPUT_VARIABLE PIXIE_BUILD_REVISION OUTPUT_STRIP_TRAILING_WHITESPACE)
  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()
target_compile_definitions(_core PRIVATE PIXIE_PY_CORE_REVISION="${PIXIE_BUILD_REVISION}")
install(TARGETS _core LIBRARY DESTINATION pixie)
