# FindDependencies.cmake - Find and configure required dependencies

# Find nlohmann/json
find_package(nlohmann_json QUIET)
if(NOT nlohmann_json_FOUND)
    message(STATUS "nlohmann_json not found, will use FetchContent")
    include(FetchContent)
    FetchContent_Declare(
        json
        GIT_REPOSITORY https://github.com/nlohmann/json.git
        GIT_TAG v3.11.2
    )
    FetchContent_MakeAvailable(json)
    set(NLOHMANN_JSON_TARGET nlohmann_json::nlohmann_json)
else()
    set(NLOHMANN_JSON_TARGET nlohmann_json::nlohmann_json)
    message(STATUS "Found nlohmann_json: ${nlohmann_json_VERSION}")
endif()

# Find httplib
find_package(httplib QUIET)
if(NOT httplib_FOUND)
    message(STATUS "httplib not found, will use FetchContent")
    include(FetchContent)
    FetchContent_Declare(
        httplib
        GIT_REPOSITORY https://github.com/yhirose/cpp-httplib.git
        GIT_TAG v0.14.1
    )
    FetchContent_MakeAvailable(httplib)
    set(HTTPLIB_TARGET httplib)
else()
    set(HTTPLIB_TARGET httplib::httplib)
    message(STATUS "Found httplib: ${httplib_VERSION}")
endif()

# Find threads
find_package(Threads REQUIRED)

# Check for CUDA
if(SD_CUDA_SUPPORT)
    find_package(CUDA QUIET)
    if(CUDA_FOUND)
        message(STATUS "Found CUDA: ${CUDA_VERSION}")
        enable_language(CUDA)
    else()
        message(WARNING "CUDA not found, disabling CUDA support")
        set(SD_CUDA_SUPPORT OFF)
    endif()
endif()

# Find OpenMP
find_package(OpenMP)
if(OpenMP_CXX_FOUND)
    message(STATUS "Found OpenMP: ${OpenMP_CXX_VERSION}")
else()
    message(WARNING "OpenMP not found")
endif()

# Find OpenSSL for SHA256 hashing
find_package(OpenSSL REQUIRED)
if(OpenSSL_FOUND)
    message(STATUS "Found OpenSSL: ${OPENSSL_VERSION}")
else()
    message(FATAL_ERROR "OpenSSL not found - required for model hashing")
endif()

# Find PAM if enabled
if(ENABLE_PAM_AUTH)
    find_package(PAM)
    if(PAM_FOUND)
        message(STATUS "Found PAM: ${PAM_VERSION}")
        list(APPEND DEPENDENCY_LIBRARIES PAM::PAM)
    else()
        message(WARNING "PAM not found, PAM authentication will be disabled")
        set(ENABLE_PAM_AUTH OFF)
    endif()
endif()

# Set up variables for targets
set(DEPENDENCY_LIBRARIES
    ${NLOHMANN_JSON_TARGET}
    ${HTTPLIB_TARGET}
    Threads::Threads
    OpenSSL::Crypto
)

if(OpenMP_CXX_FOUND)
    list(APPEND DEPENDENCY_LIBRARIES OpenMP::OpenMP_CXX)
endif()

message(STATUS "Dependencies configured successfully")