# If leaks are found, abort() during interpreter shutdown to catch this in the CI
add_definitions(-DNB_ABORT_ON_LEAK)

if (NB_TEST_STABLE_ABI)
  set(NB_EXTRA_ARGS ${NB_EXTRA_ARGS} STABLE_ABI)
endif()

if (NB_TEST_FREE_THREADED)
  set(NB_EXTRA_ARGS ${NB_EXTRA_ARGS} FREE_THREADED)
endif()

if (NB_TEST_SHARED_BUILD)
  set(NB_EXTRA_ARGS ${NB_EXTRA_ARGS} NB_SHARED)
endif()

# Extension flavor keywords without the backend-selecting ones, for test
# extensions that pick their own backend below
set(NB_FLAVOR_ARGS "")
if (NB_TEST_FREE_THREADED)
  set(NB_FLAVOR_ARGS FREE_THREADED)
endif()

# NB_TEST_SPLIT_MODE runs the test suite in split mode: every test extension
# resolves the compiled backend from a backend module at import time.
# NB_TEST_SPLIT_WHEEL routes the suite through the installed
# 'nanobind_backend' module (from the nanobind-backend wheel) instead of a
# locally built one. Both are internal testing knobs passed via -D.
if (NB_TEST_SPLIT_MODE)
  if (NB_FREE_THREADED AND NOT NB_TEST_FREE_THREADED)
    message(FATAL_ERROR "NB_TEST_SPLIT_MODE=ON on a free-threaded interpreter "
      "requires NB_TEST_FREE_THREADED=ON (a free-threaded backend serves "
      "only free-threaded extensions)")
  endif()

  # Build a local backend module and route every test extension through it
  nanobind_add_backend(nanobind_backend_test)

  # Stub generation imports the extensions, which need their backend
  set(NB_BACKEND_DEPENDS nanobind_backend_test)

  if (NB_TEST_SPLIT_WHEEL)
    # The local backend above still serves the fill() handshake tests
    set(NB_EXTRA_ARGS ${NB_EXTRA_ARGS} BACKEND_MODULE nanobind_backend)
  else()
    set(NB_EXTRA_ARGS ${NB_EXTRA_ARGS} BACKEND_MODULE nanobind_backend_test)
  endif()
endif()

# NB_EXTRA_ARGS for test extensions in the 'mydomain' domain. In split mode,
# these share the backend module with everything else; the domain isolates
# their type universe regardless.
set(NB_EXTRA_ARGS_MYDOMAIN ${NB_EXTRA_ARGS} NB_DOMAIN mydomain)

# ---------------------------------------------------------------------------
# Compile with a few more compiler warnings turned on
# ---------------------------------------------------------------------------

if (MSVC)
  if (CMAKE_CXX_FLAGS MATCHES "/W[0-4]")
    string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
  elseif (NOT NB_TEST_CUDA)
    add_compile_options(/W4)
  endif()
elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU|IntelLLVM")
  # Not enabling -Werror on CUDA compiler because of many visibility attribute warnings in tests
  add_compile_options(
      $<$<COMPILE_LANGUAGE:CXX>:-Werror>
      # $<$<COMPILE_LANGUAGE:CUDA>:--compiler-options=-Werror>
      -Wall -Wextra -Wconversion
  )
endif()

if (UNIX AND (CMAKE_SIZEOF_VOID_P EQUAL 4) AND (CMAKE_SYSTEM_PROCESSOR STREQUAL i686))
  # Don't use the legacy 387 math coprocessor in 32 bit builds, this causes tests to fail
  add_compile_options(-mfpmath=sse -msse2)
endif()

# Enforce the use of the CUDA NVCC compiler if requested
if (NB_TEST_CUDA)
  enable_language(CUDA)
  set(CMAKE_CUDA_STANDARD 17)
  set(CMAKE_CUDA_STANDARD_REQUIRED ON)
endif()

set(NB_TEST_SANITIZER "")

if (NB_TEST_SANITIZERS_ASAN)
  list(APPEND NB_TEST_SANITIZERS address)
endif()

if (NB_TEST_SANITIZERS_UBSAN)
  list(APPEND NB_TEST_SANITIZERS undefined)
endif()

if (NB_TEST_SANITIZERS_TSAN)
  list(APPEND NB_TEST_SANITIZERS thread)
endif()


if (NB_TEST_SANITIZERS)
  string(REPLACE ";" "," NB_TEST_SANITIZERS "${NB_TEST_SANITIZERS}")
  add_compile_options(-fsanitize=${NB_TEST_SANITIZERS})
  add_link_options(-fsanitize=${NB_TEST_SANITIZERS})
endif()

set(TEST_NAMES
  accessor
  functions
  callbacks
  classes
  holders
  stl
  stl_bind_map
  stl_bind_vector
  chrono
  enum
  eval
  ndarray
  jax
  tensorflow
  exception
  make_iterator
  typing
  issue
  intrusive
  thread
)

foreach (NAME ${TEST_NAMES})
  if (NAME STREQUAL classes)
    nanobind_add_module(test_${NAME}_ext test_${NAME}.cpp test_${NAME}_extra.cpp ${NB_EXTRA_ARGS})
  else()
    nanobind_add_module(test_${NAME}_ext test_${NAME}.cpp ${NB_EXTRA_ARGS})
  endif()

  if (NB_TEST_CUDA)
    set_property(SOURCE test_${NAME}.cpp PROPERTY LANGUAGE CUDA)
  endif()
endforeach()

target_sources(test_intrusive_ext PRIVATE test_intrusive_impl.cpp)

# Compile-time freeze checks for the frozen ABI surface of nb_backend.h
target_sources(test_functions_ext PRIVATE test_abi_layout.cpp)

if (CMAKE_CONFIGURATION_TYPES)
  set(OUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>)
else()
  set(OUT_DIR ${CMAKE_CURRENT_BINARY_DIR})
endif()

foreach (NAME functions classes ndarray jax tensorflow stl enum typing make_iterator)
  if (NAME STREQUAL typing)
    set(EXTRA
      MARKER_FILE py.typed
      PATTERN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/pattern_file.nb"
      EXCLUDE_VALUES
    )
    set(EXTRA_DEPENDS "${OUT_DIR}/py_stub_test.py")
  else()
    set(EXTRA "")
    set(EXTRA_DEPENDS "")
  endif()

  if (CMAKE_CONFIGURATION_TYPES)
    # On multi-config generators like Visual Studio, put stubs in the 'Debug' / 'Release' /.. folders
    set(PYI_PREFIX $<CONFIG>/)
  endif()

  nanobind_add_stub(
    ${NAME}_ext_stub
    MODULE test_${NAME}_ext
    OUTPUT ${PYI_PREFIX}test_${NAME}_ext.pyi
    PYTHON_PATH $<TARGET_FILE_DIR:test_${NAME}_ext>
    DEPENDS test_${NAME}_ext ${EXTRA_DEPENDS} ${NB_BACKEND_DEPENDS}
    ${EXTRA})
endforeach()

# Check the version manually: Eigen's "SameMajorVersion" config rejects ranges like "3...5"
find_package (Eigen3 NO_MODULE)
if (TARGET Eigen3::Eigen AND Eigen3_VERSION VERSION_GREATER_EQUAL 3.3.1)
  nanobind_add_module(test_eigen_ext test_eigen.cpp ${NB_EXTRA_ARGS})
  target_link_libraries(test_eigen_ext PRIVATE Eigen3::Eigen)
  nanobind_add_module(test_eigen_tensor_ext test_eigen_tensor.cpp ${NB_EXTRA_ARGS})
  target_link_libraries(test_eigen_tensor_ext PRIVATE Eigen3::Eigen)
endif()

add_library(
  inter_module
  SHARED
  inter_module.h
  inter_module.cpp
)

target_compile_definitions(inter_module PRIVATE -DSHARED_BUILD)
target_compile_features(inter_module PRIVATE cxx_std_17)
target_include_directories(inter_module PRIVATE ${NB_DIR}/include)

# An extension that sets up nanobind via nb::register_module() instead of NB_MODULE()
nanobind_add_module(test_foreign_ext test_foreign.cpp ${NB_EXTRA_ARGS})

nanobind_add_module(test_inter_module_1_ext test_inter_module_1.cpp ${NB_EXTRA_ARGS_MYDOMAIN})
nanobind_add_module(test_inter_module_2_ext test_inter_module_2.cpp ${NB_EXTRA_ARGS_MYDOMAIN})
target_link_libraries(test_inter_module_1_ext PRIVATE inter_module)
target_link_libraries(test_inter_module_2_ext PRIVATE inter_module)

if (NB_TEST_SPLIT_MODE)
  # Bindings spread over two translation units that exchange bound types;
  # validates that the per-DSO dispatch table merges into a single instance.
  # The LTO twin re-checks this under interprocedural optimization.
  set(NB_ABI_MULTI_SOURCES test_abi_multi_1.cpp test_abi_multi_2.cpp)
  nanobind_add_module(test_abi_multi_ext ${NB_ABI_MULTI_SOURCES}
    ${NB_EXTRA_ARGS})
  nanobind_add_module(test_abi_multi_lto_ext ${NB_ABI_MULTI_SOURCES} LTO
    ${NB_EXTRA_ARGS})
  target_compile_definitions(test_abi_multi_lto_ext PRIVATE
    NB_ABI_MULTI_NAME=test_abi_multi_lto_ext NB_ABI_MULTI_NS=abi_multi_lto)

  # Points at a backend module that does not exist; its import must fail
  # with an instructive error message
  nanobind_add_module(test_abi_missing_ext test_abi_missing.cpp
    BACKEND_MODULE nanobind_backend_absent ${NB_FLAVOR_ARGS})
endif()

set(TEST_FILES
  common.py
  conftest.py
  test_accessor.py
  test_callbacks.py
  test_classes.py
  test_eigen.py
  test_eigen_tensor.py
  test_enum.py
  test_eval.py
  test_exception.py
  test_foreign.py
  test_functions.py
  test_holders.py
  test_inter_module.py
  test_intrusive.py
  test_make_iterator.py
  test_stl.py
  test_stl_bind_map.py
  test_stl_bind_vector.py
  test_chrono.py
  test_ndarray.py
  test_jax.py
  test_tensorflow.py
  test_stubs.py
  test_stubgen.py
  test_typing.py
  test_thread.py
  test_specialization.py
  test_abi.py

  # Stub reference files
  test_classes_ext.pyi.ref
  test_functions_ext.pyi.ref
  test_make_iterator_ext.pyi.ref
  test_ndarray_ext.pyi.ref
  test_jax_ext.pyi.ref
  test_tensorflow_ext.pyi.ref
  test_stl_ext.pyi.ref
  test_enum_ext.pyi.ref
  test_typing_ext.pyi.ref
  py_stub_test.py
  py_stub_test.pyi.ref
  py_recursive_stub_test/__init__.pyi.ref
  py_recursive_stub_test/alias.pyi.ref
  py_recursive_stub_test/bar.pyi.ref
  py_recursive_stub_test/sub/__init__.pyi.ref
  py_recursive_stub_test/sub/mod.pyi.ref
  test_prefix_module/__init__.pyi.ref
  test_prefix_module/prefix.pyi.ref
  test_prefix_module/prefixabc.pyi.ref
)

set (PY_STUB_TEST py_stub_test.py)
if (NOT (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR) OR MSVC)
  foreach(TEST_FILE IN LISTS TEST_FILES)
    set(IN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/${TEST_FILE})
    set(OUT_FILE ${OUT_DIR}/${TEST_FILE})
    set(TEST_FILES_OUT ${TEST_FILES_OUT} ${OUT_FILE})
    add_custom_command(
      DEPENDS ${IN_FILE} OUTPUT ${OUT_FILE}
      COMMAND ${CMAKE_COMMAND} -E copy_if_different ${IN_FILE} ${OUT_FILE})
  endforeach()

  # The unit tests in test_stubgen.py need a copy of stubgen.py next to them
  add_custom_command(
    DEPENDS ${NB_DIR}/src/stubgen.py OUTPUT ${OUT_DIR}/stubgen.py
    COMMAND ${CMAKE_COMMAND} -E copy_if_different ${NB_DIR}/src/stubgen.py ${OUT_DIR}/stubgen.py)

  add_custom_target(copy-tests ALL DEPENDS ${TEST_FILES_OUT} ${OUT_DIR}/stubgen.py)
  set(PY_STUB_TEST ${OUT_DIR}/py_stub_test.py)
endif()

nanobind_add_stub(
  py_stub
  MODULE py_stub_test
  OUTPUT ${PYI_PREFIX}py_stub_test.pyi
  PYTHON_PATH $<TARGET_FILE_DIR:test_stl_ext>
  DEPENDS ${PY_STUB_TEST}
)

nanobind_add_stub(
  py_recursive_stub
  RECURSIVE
  MODULE py_recursive_stub_test
  OUTPUT_PATH
    ${PYI_PREFIX}py_recursive_stub_test
  OUTPUT
    ${PYI_PREFIX}py_recursive_stub_test/__init__.pyi
    ${PYI_PREFIX}py_recursive_stub_test/alias.pyi
    ${PYI_PREFIX}py_recursive_stub_test/bar.pyi
    ${PYI_PREFIX}py_recursive_stub_test/sub/__init__.pyi
    ${PYI_PREFIX}py_recursive_stub_test/sub/mod.pyi
  PATTERN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/pattern_file_recursive.nb
  PYTHON_PATH ${CMAKE_CURRENT_SOURCE_DIR}
)

nanobind_add_stub(
  test_prefix_module_stub
  RECURSIVE
  MODULE test_prefix_module
  OUTPUT_PATH
    ${PYI_PREFIX}test_prefix_module
  OUTPUT
    ${PYI_PREFIX}test_prefix_module/__init__.pyi
    ${PYI_PREFIX}test_prefix_module/prefix.pyi
    ${PYI_PREFIX}test_prefix_module/prefixabc.pyi
  PYTHON_PATH ${CMAKE_CURRENT_SOURCE_DIR}
)
