#[[
Copyright (c) 2014-2024 Key4hep-Project.

This file is part of Key4hep.
See https://key4hep.github.io/key4hep-doc/ for further info.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]

set(CATCH2_MIN_VERSION 3.5.0)

set(USE_EXTERNAL_CATCH2 AUTO CACHE STRING "Link against an external Catch2 v3 static library, otherwise build it locally")
set_property(CACHE USE_EXTERNAL_CATCH2 PROPERTY STRINGS AUTO ON OFF)

if(USE_EXTERNAL_CATCH2)
  if (USE_EXTERNAL_CATCH2 STREQUAL AUTO)
    find_package(Catch2 ${CATCH2_MIN_VERSION})
  else()
    find_package(Catch2 ${CATCH2_MIN_VERSION} REQUIRED)
  endif()
endif()

if(NOT Catch2_FOUND)
  message(STATUS "Fetching local copy of Catch2 library for unit-tests...")
  # Build Catch2 with the default flags, to avoid generating warnings when we
  # build it
  set(CXX_FLAGS_CMAKE_USED ${CMAKE_CXX_FLAGS})
  set(CMAKE_CXX_FLAGS ${CXX_FLAGS_CMAKE_DEFAULTS})
  Include(FetchContent)
  FetchContent_Declare(
    Catch2
    GIT_REPOSITORY https://github.com/catchorg/Catch2.git
    GIT_TAG        v${CATCH2_MIN_VERSION}
    )
  FetchContent_MakeAvailable(Catch2)
  set(CMAKE_MODULE_PATH ${Catch2_SOURCE_DIR}/extras ${CMAKE_MODULE_PATH})

  # Disable clang-tidy on external contents
  set_target_properties(Catch2 PROPERTIES CXX_CLANG_TIDY "")

  # Hack around the fact, that the include directories are not declared as
  # SYSTEM for the targets defined this way. Otherwise warnings can still occur
  # in Catch2 code when templates are evaluated (which happens quite a bit)
  get_target_property(CATCH2_IF_INC_DIRS Catch2 INTERFACE_INCLUDE_DIRECTORIES)
  set_target_properties(Catch2 PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${CATCH2_IF_INC_DIRS}")

  # Reset the flags
  set(CMAKE_CXX_FLAGS ${CXX_FLAGS_CMAKE_USED})
else()
  # Same hack as above for the system-installed Catch2: mark its include
  # directories as SYSTEM to suppress warnings from Catch2 headers
  get_target_property(CATCH2_IF_INC_DIRS Catch2::Catch2 INTERFACE_INCLUDE_DIRECTORIES)
  set_target_properties(Catch2::Catch2 PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${CATCH2_IF_INC_DIRS}")
endif()

# The key4hep stack ships its own copies of the libraries built here
# (libk4ActsTracking.so, libGNNTracking*.so), and its lib directory ends up on
# LD_LIBRARY_PATH. CMake emits the build tree rpath as DT_RUNPATH, which the
# dynamic loader searches *after* LD_LIBRARY_PATH, so the stack copy shadows the
# one that was just built. Any symbol that only exists in the local build then
# fails to resolve at run time, both when catch_discover_tests runs the binary at
# build time to enumerate the test cases and when ctest runs it later.
#
# The DL_PATHS below put the build tree ahead of the stack on LD_LIBRARY_PATH for
# both of those, so the freshly built libraries win. This is the same shadowing
# that the LD_PRELOAD in ../CMakeLists.txt works around for the Gaudi plugin
# module; that test environment does not apply here because test discovery
# happens at build time. DL_PATHS is what sets the CMake 3.22 floor of this
# project.
add_executable(unittest_k4ActsTracking CellIDSelectionTests.cpp HitFeatureTests.cpp)
target_link_libraries(unittest_k4ActsTracking PUBLIC k4ActsTracking PRIVATE Catch2::Catch2WithMain)
# Catch2 TEST_CASE/SECTION macros expand __COUNTER__ at the call site in user
# code, so marking Catch2 headers as system includes is not sufficient to
# suppress this warning, present with Clang 22
target_compile_options(unittest_k4ActsTracking PRIVATE -Wno-c2y-extensions)

include(Catch)
catch_discover_tests(unittest_k4ActsTracking
  WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
  TEST_PREFIX "UT_" # make it possible to filter easily with -R ^UT
  DL_PATHS $<TARGET_FILE_DIR:k4ActsTracking> # see the shadowing note above
)

# GNN track finding: unit tests for the mlutils helpers in ONNXInferenceModel.h.
# The GNNTrackingONNXInferenceModels usage requirements provide the
# GNNTrackFinding/include directory, so no extra include path is needed here.
# Only built when the GNN track finding code is enabled (it provides the
# GNNTrackingONNXInferenceModels target this test links against).
if(K4ACTSTRACKING_BUILD_GNN)
  add_executable(unittest_gnntrackfinding ONNXInferenceModelTests.cpp)
  target_link_libraries(unittest_gnntrackfinding
    PUBLIC GNNTrackingONNXInferenceModels
    PRIVATE Catch2::Catch2WithMain)
  target_compile_options(unittest_gnntrackfinding PRIVATE -Wno-c2y-extensions)

  catch_discover_tests(unittest_gnntrackfinding
    WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
    TEST_PREFIX "UT_" # make it possible to filter easily with -R ^UT
    # see the shadowing note above, the stack ships this library too
    DL_PATHS $<TARGET_FILE_DIR:GNNTrackingONNXInferenceModels>
  )
endif()
