set(
    FESA_GTEST_SOURCE_DIR
    ""
    CACHE PATH
    "Path to the approved local GoogleTest source checkout"
)

if(NOT FESA_GTEST_SOURCE_DIR)
    message(FATAL_ERROR "FESA_GTEST_SOURCE_DIR must name a local GoogleTest source checkout")
endif()

get_filename_component(
    _fesa_gtest_source_dir
    "${FESA_GTEST_SOURCE_DIR}"
    ABSOLUTE
    BASE_DIR "${CMAKE_SOURCE_DIR}"
)

if(NOT EXISTS "${_fesa_gtest_source_dir}/CMakeLists.txt")
    message(
        FATAL_ERROR
        "FESA_GTEST_SOURCE_DIR does not contain a GoogleTest CMakeLists.txt: "
        "${_fesa_gtest_source_dir}"
    )
endif()

# Keep GoogleTest on the same MSVC runtime as FESA without changing its source tree.
set(gtest_force_shared_crt ON CACHE BOOL "Use the shared MSVC runtime for GoogleTest" FORCE)
add_subdirectory(
    "${_fesa_gtest_source_dir}"
    "${CMAKE_BINARY_DIR}/_deps/googletest-build"
    EXCLUDE_FROM_ALL
)

find_package(MKL CONFIG REQUIRED)
find_package(TBB CONFIG REQUIRED COMPONENTS tbb)
find_package(HDF5 CONFIG REQUIRED)

if(NOT TARGET MKL::MKL)
    message(FATAL_ERROR "The oneMKL CONFIG package did not define MKL::MKL")
endif()

if(NOT TARGET TBB::tbb)
    message(FATAL_ERROR "The oneTBB CONFIG package did not define TBB::tbb")
endif()

# Prefer the packaged shared C runtime when both variants exist. The Windows
# static archive may carry compiler-runtime requirements that are not part of
# the HDF5 imported target's transitive link interface.
if(TARGET hdf5::hdf5-shared)
    set(_fesa_hdf5_target hdf5::hdf5-shared)
elseif(TARGET hdf5::hdf5-static)
    set(_fesa_hdf5_target hdf5::hdf5-static)
elseif(TARGET HDF5::HDF5)
    set(_fesa_hdf5_target HDF5::HDF5)
else()
    message(FATAL_ERROR "The HDF5 CONFIG package did not define a supported C target")
endif()

# Stable FESA-owned targets keep package-specific target names out of later modules.
add_library(fesa_dependency_mkl INTERFACE)
target_link_libraries(fesa_dependency_mkl INTERFACE MKL::MKL)
add_library(Fesa::MKL ALIAS fesa_dependency_mkl)

add_library(fesa_dependency_tbb INTERFACE)
target_link_libraries(fesa_dependency_tbb INTERFACE TBB::tbb)
add_library(Fesa::TBB ALIAS fesa_dependency_tbb)

add_library(fesa_dependency_hdf5 INTERFACE)
target_link_libraries(fesa_dependency_hdf5 INTERFACE "${_fesa_hdf5_target}")
add_library(Fesa::HDF5 ALIAS fesa_dependency_hdf5)

unset(_fesa_gtest_source_dir)
unset(_fesa_hdf5_target)
