cmake_minimum_required(VERSION 3.24)
project(hpr_toolchain_check LANGUAGES C CXX CUDA)
find_package(CUDAToolkit REQUIRED)
find_package(ZLIB REQUIRED)
find_library(HPR_CRYPTO NAMES libcrypto.so.3 libcrypto.so.1.1 REQUIRED)

string(REGEX MATCH "^[0-9]+\\.[0-9]+" nvcc_mm "${CMAKE_CUDA_COMPILER_VERSION}")
string(REGEX MATCH "^[0-9]+\\.[0-9]+" toolkit_mm "${CUDAToolkit_VERSION}")
if(NOT nvcc_mm STREQUAL toolkit_mm)
    message(FATAL_ERROR "Mixed CUDA toolchain: nvcc ${nvcc_mm}, libraries/headers ${toolkit_mm}. Set CUDA_HOME to a complete matching toolkit.")
endif()

set(runtime_dirs "")
foreach(component cudart cublas cublasLt cusparse cufft cusolver)
    if(NOT TARGET CUDA::${component})
        message(FATAL_ERROR "CUDA ${component} development library missing from ${CUDAToolkit_ROOT}. Install a complete toolkit.")
    endif()
    get_target_property(library CUDA::${component} IMPORTED_LOCATION)
    if(NOT EXISTS "${library}" OR library MATCHES "/stubs/")
        message(FATAL_ERROR "CUDA ${component} has no usable runtime library: ${library}")
    endif()
    get_filename_component(directory "${library}" DIRECTORY)
    list(APPEND runtime_dirs "${directory}")
    file(REAL_PATH "${library}" real_library)
    get_filename_component(real_directory "${real_library}" DIRECTORY)
    list(APPEND runtime_dirs "${real_directory}")
endforeach()
# Some Toolkit dependencies reside next to cudart rather than the linker alias.
if(IS_DIRECTORY "${CUDAToolkit_LIBRARY_DIR}" AND NOT CUDAToolkit_LIBRARY_DIR MATCHES "/stubs($|/)")
    list(APPEND runtime_dirs "${CUDAToolkit_LIBRARY_DIR}")
endif()
list(REMOVE_DUPLICATES runtime_dirs)
list(JOIN runtime_dirs "\n" runtime_lines)
file(WRITE "${CMAKE_BINARY_DIR}/cuda-runtime-dirs.txt" "${runtime_lines}\n")
message(STATUS "HPR CUDA runtime directories: ${runtime_dirs}")

# Reuse the upstream startup check before choosing an automatic candidate.
# This probes an existing driver; it never installs one. A hidden GPU remains
# explicitly unverified, matching the upstream build policy.
execute_process(COMMAND "${Python3_EXECUTABLE}"
    "${CMAKE_CURRENT_LIST_DIR}/../../vendor/HPR-QP-C/scripts/configure_cuda_runtime.py"
    --cuda-root "${CUDAToolkit_ROOT}" --nvcc "${CMAKE_CUDA_COMPILER}"
    --cc "${CMAKE_C_COMPILER}" --output "${CMAKE_BINARY_DIR}/cuda-runtime.json"
    RESULT_VARIABLE driver_result)
if(NOT driver_result EQUAL 0)
    message(FATAL_ERROR "CUDA startup validation failed for this candidate; see cuda-runtime.json and the probe output.")
endif()
