# The function runner's execution core.
#
# This directory builds two ways: as a subdirectory of the root project, and as
# a project of its own (`cmake -S runner -B build-runner`). The second is how it
# gets built and tested on the dev host, where the root project cannot configure
# at all because smartbotic-db-client is unbuildable there (see CLAUDE.md).
if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
    cmake_minimum_required(VERSION 3.20)
    project(smartbotic-vectorapi-runner LANGUAGES C CXX)
    set(CMAKE_CXX_STANDARD 20)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    set(CMAKE_CXX_EXTENSIONS OFF)
    if(NOT CMAKE_BUILD_TYPE)
        set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Build type" FORCE)
    endif()
    option(BUILD_TESTS "Build tests" ON)
    enable_testing()
endif()

# QuickJS is C, and the root project declares CXX only.
enable_language(C)

#
# Deliberately self-contained: it links neither vectorapi_core nor
# smartbotic-db-client, so it configures, builds and tests on the dev host whose
# protobuf is too new for the database client (see CLAUDE.md gotchas). The
# host-binding workstream that does need the gateway links THAT on top of this
# target, it does not move the dependency in here.

include(FetchContent)

# quickjs-ng rather than Bellard's quickjs: it ships a real CMake build, exports
# the module/promise/bytecode entry points we need as public API
# (JS_GetModuleNamespace, JS_PromiseState, JS_SetMaxStackSize), builds clean
# under a C++ TU's expectations, and is the variant that is actually maintained.
# Pinned to an exact tag - bytecode has no version stamp, so a silent QuickJS
# upgrade would make cached blobs misread.
set(SVAPI_QUICKJS_TAG "v0.17.0" CACHE STRING "quickjs-ng git tag to vendor")

set(QJS_ENABLE_INSTALL OFF CACHE BOOL "" FORCE)   # quickjs must not land in our .deb
set(QJS_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(QJS_BUILD_LIBC OFF CACHE BOOL "" FORCE)       # no std/os modules: slice 1 has no filesystem
set(QJS_BUILD_CLI_WITH_MIMALLOC OFF CACHE BOOL "" FORCE)
set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)

# quickjs-ng adds qjs/qjsc/api-test unconditionally; EXCLUDE_FROM_ALL keeps them
# out of our default build. The guard is for CMake < 3.28, where the option does
# not exist yet and the extra targets are merely wasted build time.
if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.28)
    FetchContent_Declare(quickjs
        GIT_REPOSITORY https://github.com/quickjs-ng/quickjs.git
        GIT_TAG        ${SVAPI_QUICKJS_TAG}
        GIT_SHALLOW    TRUE
        EXCLUDE_FROM_ALL)
else()
    FetchContent_Declare(quickjs
        GIT_REPOSITORY https://github.com/quickjs-ng/quickjs.git
        GIT_TAG        ${SVAPI_QUICKJS_TAG}
        GIT_SHALLOW    TRUE)
endif()
FetchContent_MakeAvailable(quickjs)

# Found by the root project already; the guard is what makes this directory
# usable on its own.
if(NOT TARGET nlohmann_json::nlohmann_json)
    find_package(nlohmann_json REQUIRED)
endif()

add_library(runner_core STATIC
    src/js_runtime.cpp)
target_include_directories(runner_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(runner_core PUBLIC nlohmann_json::nlohmann_json PRIVATE qjs)
target_compile_features(runner_core PUBLIC cxx_std_20)
set_target_properties(runner_core PROPERTIES POSITION_INDEPENDENT_CODE ON)

find_package(Threads REQUIRED)
target_link_libraries(runner_core PUBLIC Threads::Threads)

# Headers shared with the server: apikey.hpp (KeyScope) and
# functions/descriptor.hpp. Both are pure, which is why the protocol layer may
# use them without dragging in the database client.
set(SVAPI_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../src")

# /run, /validate and /health as JSON in, JSON out: no transport, no database,
# which is what keeps the protocol testable on the dev host.
add_library(runner_protocol STATIC src/run_service.cpp)
target_include_directories(runner_protocol PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}/src
    ${SVAPI_SRC_DIR})
target_link_libraries(runner_protocol PUBLIC runner_core nlohmann_json::nlohmann_json)
target_compile_features(runner_protocol PUBLIC cxx_std_20)
set_target_properties(runner_protocol PROPERTIES POSITION_INDEPENDENT_CODE ON)

if(BUILD_TESTS)
    # Same find-then-fetch dance as tests/CMakeLists.txt, guarded so that
    # wiring this directory into the root project does not fetch twice.
    if(NOT TARGET GTest::gtest_main)
        find_package(GTest QUIET)
        if(NOT GTest_FOUND)
            message(STATUS "GTest not found on the system - fetching googletest")
            FetchContent_Declare(googletest
                GIT_REPOSITORY https://github.com/google/googletest.git
                GIT_TAG        v1.15.2)
            set(INSTALL_GTEST OFF CACHE BOOL "" FORCE)
            FetchContent_MakeAvailable(googletest)
        endif()
    endif()
    include(GoogleTest)

    add_executable(test_js_runtime tests/js_runtime_test.cpp)
    target_link_libraries(test_js_runtime PRIVATE runner_core GTest::gtest_main)
    gtest_discover_tests(test_js_runtime PROPERTIES TIMEOUT 120)

    if(NOT TARGET OpenSSL::Crypto)
        find_package(OpenSSL REQUIRED)   # apikey.cpp uses RAND_bytes
    endif()
    # Compiles the two pure server sources directly rather than linking
    # vectorapi_core, the same approach tests/CMakeLists.txt uses, so this
    # target still builds where smartbotic-db-client cannot.
    add_executable(test_run_service
        tests/run_service_test.cpp
        ${SVAPI_SRC_DIR}/functions/descriptor.cpp
        ${SVAPI_SRC_DIR}/apikey.cpp)
    target_link_libraries(test_run_service PRIVATE
        runner_protocol OpenSSL::Crypto GTest::gtest_main)
    gtest_discover_tests(test_run_service PROPERTIES TIMEOUT 120)
endif()

# The host bindings: the ctx.* surface. A SEPARATE target from runner_core
# because this is the half that links vectorapi_core and the database client,
# which is exactly why runner_core itself still builds and tests on the dev
# host (CLAUDE.md). Guarded, so configuring runner/ standalone still works.
if(TARGET vectorapi_core)
    # The JS prelude is embedded as a raw string literal, so the binary carries
    # no runtime file dependency: a deployed runner cannot be made to execute a
    # different prelude by swapping a file beside it.
    set(SVAPI_HOST_PRELUDE "${CMAKE_CURRENT_SOURCE_DIR}/src/host_prelude.js")
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${SVAPI_HOST_PRELUDE}")
    file(READ "${SVAPI_HOST_PRELUDE}" SVAPI_HOST_PRELUDE_TEXT)
    file(CONFIGURE
        OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/generated/host_prelude_js.hpp"
        CONTENT "#pragma once
// GENERATED from runner/src/host_prelude.js - do not edit.
namespace svapi::runner::generated {
inline constexpr const char* kHostPreludeJs = R\"JS(
${SVAPI_HOST_PRELUDE_TEXT})JS\";
} // namespace svapi::runner::generated
"
        @ONLY)

    add_library(runner_host STATIC src/host_context.cpp)
    target_include_directories(runner_host PUBLIC ${CMAKE_CURRENT_BINARY_DIR}/generated)
    # qjs again, PRIVATE on runner_core: host_context.cpp includes quickjs.h.
    target_link_libraries(runner_host PUBLIC runner_core vectorapi_core PRIVATE qjs)
    target_compile_features(runner_host PUBLIC cxx_std_20)
    set_target_properties(runner_host PROPERTIES POSITION_INDEPENDENT_CODE ON)

    if(BUILD_TESTS)
        add_executable(test_host_context tests/host_context_test.cpp)
        target_link_libraries(test_host_context PRIVATE runner_host GTest::gtest_main)
        gtest_discover_tests(test_host_context PROPERTIES TIMEOUT 120)
    endif()
endif()

# The binary links vectorapi_core (registry + gateway) and host_context.cpp, and
# includes <svapi/version.hpp>, which only the root project generates. So it
# exists only inside the root project; a standalone runner build stops at the
# protocol layer and its tests.
if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
    add_executable(smartbotic-vectorapi-runner src/main.cpp)
    target_link_libraries(smartbotic-vectorapi-runner PRIVATE
        runner_protocol runner_host vectorapi_core
        $<$<BOOL:${SYSTEMD_FOUND}>:PkgConfig::SYSTEMD>)
    if(SYSTEMD_FOUND)
        target_compile_definitions(smartbotic-vectorapi-runner PRIVATE HAVE_SYSTEMD)
    endif()
    install(TARGETS smartbotic-vectorapi-runner RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()
