cmake_minimum_required(VERSION 3.18)
project(qestats LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# ── Python ────────────────────────────────────────────────────────────────────
find_package(Python REQUIRED COMPONENTS Interpreter Development.Module)

# ── nanobind (locate via the Python package, works with pip or homebrew) ──────
execute_process(
    COMMAND "${Python_EXECUTABLE}" -c "import nanobind; print(nanobind.cmake_dir())"
    OUTPUT_STRIP_TRAILING_WHITESPACE
    OUTPUT_VARIABLE NB_CMAKE_DIR
    RESULT_VARIABLE NB_RESULT
)
if(NOT NB_RESULT EQUAL 0)
    message(FATAL_ERROR "Could not locate nanobind cmake directory. "
            "Install it with: pip install nanobind")
endif()
list(PREPEND CMAKE_PREFIX_PATH "${NB_CMAKE_DIR}")
find_package(nanobind CONFIG REQUIRED)

# ── libqe-stats headers ───────────────────────────────────────────────────────
# Canonical location is the repo root include/.  An sdist only contains python/,
# so scripts/sync-headers.sh copies them to python/include/ first; prefer that
# copy when present, else build in-tree from ../include.  Header-only, no
# dependencies beyond the C++ standard library.
set(QESTATS_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include")
if(NOT EXISTS "${QESTATS_INCLUDE_DIR}/qestats/qestats.hpp")
    set(QESTATS_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../include")
endif()
if(NOT EXISTS "${QESTATS_INCLUDE_DIR}/qestats/qestats.hpp")
    message(FATAL_ERROR "libqe-stats headers not found in python/include/ or ../include/. "
            "Building from a git checkout needs ../include/qestats/qestats.hpp; an sdist "
            "needs scripts/sync-headers.sh run before it is built.")
endif()

# ── binding module ────────────────────────────────────────────────────────────
nanobind_add_module(_qestats NB_STATIC src/qestats.cpp)
target_include_directories(_qestats PRIVATE ${QESTATS_INCLUDE_DIR})

install(TARGETS _qestats LIBRARY DESTINATION qestats)
