# Builds the gk-server engine (the gguf-server LLM HTTP server running on gk)
# from the vendored source tree and installs the binary into the gk_server
# package, where the Python backend spawns it. Modeled on the ggk and
# gguf-server CMakeLists.txt; this is the server half of the ggk split.
cmake_minimum_required(VERSION 3.15)
project(gk_server C CXX)

option(GK_SERVER_BUILD "Build the gk-server engine and install it alongside the python package" ON)

if(NOT GK_SERVER_BUILD)
    return()
endif()

if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
endif()

# ── Locate the engine source tree ────────────────────────────────────────────
set(GK_SERVER_ENGINE_DIR "" CACHE PATH "Path to the gk-server engine source tree")
if(NOT GK_SERVER_ENGINE_DIR AND DEFINED ENV{GK_SERVER_ENGINE_DIR})
    set(GK_SERVER_ENGINE_DIR "$ENV{GK_SERVER_ENGINE_DIR}")
endif()
if(NOT GK_SERVER_ENGINE_DIR AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/vendor/server/CMakeLists.txt")
    set(GK_SERVER_ENGINE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/vendor/server")
endif()
if(NOT GK_SERVER_ENGINE_DIR OR NOT EXISTS "${GK_SERVER_ENGINE_DIR}/app/CMakeLists.txt")
    message(FATAL_ERROR
        "gk-server engine source not found. Provide it via one of:\n"
        "  - the vendored copy at vendor/server (see scripts/vendor_engine.py)\n"
        "  - -DGK_SERVER_ENGINE_DIR=/path/to/engine or the same env var")
endif()
get_filename_component(GK_SERVER_ENGINE_DIR "${GK_SERVER_ENGINE_DIR}" ABSOLUTE)
message(STATUS "gk-server: engine source at ${GK_SERVER_ENGINE_DIR}")

# ── Option helper ────────────────────────────────────────────────────────────
# Values are read from the environment as well as -D, because `pip install`
# makes environment variables far easier to pass than CMake defines:
#   GK_SERVER_CUDA=1 pip install .
#   CMAKE_ARGS="-DGK_SERVER_CUDA=ON" pip install .
function(gk_server_option name docstring default)
    if(DEFINED ENV{${name}} AND NOT "$ENV{${name}}" STREQUAL "")
        set(default "$ENV{${name}}")
    endif()
    option(${name} "${docstring}" "${default}")
endfunction()

# ── Windows / MinGW toolchain fixes ──────────────────────────────────────────
if(WIN32 AND NOT MSVC)
    # MinGW-w64's headers pin _WIN32_WINNT to a Windows 7-era value before the
    # engine gets a chance to set it; cpp-httplib then hard-errors and
    # ::CreateFile2 goes undeclared. Set it up front, matching what the engine
    # expects everywhere else.
    add_compile_definitions(_WIN32_WINNT=0x0A00 WINVER=0x0A00 NTDDI_VERSION=0x0A000000)

    # A MinGW-built binary otherwise needs libstdc++-6.dll, libgcc_s_seh-1.dll
    # and libwinpthread-1.dll from the toolchain at run time. The wheel ships a
    # single file and Python spawns it without MSYS2 on PATH, so link the
    # runtime in.
    gk_server_option(GK_SERVER_MINGW_STATIC
        "Statically link the MinGW runtime into the engine binary" ON)
    if(GK_SERVER_MINGW_STATIC)
        # gk runs its own thread pool rather than OpenMP, so -static has no
        # libgomp import library to fight here — unlike the ggml build the
        # gguf-server package carries, where OpenMP had to be redirected or
        # dropped.
        add_link_options(-static-libgcc -static-libstdc++ -static)
    endif()
endif()

# ── Shape the engine build for a single-file wheel ───────────────────────────
# Static libs (gk, ggml-compat, llama, llama-common, mtmd, …) linked straight
# into the executable keep the wheel to one binary with no rpath/DLL handling.
set(BUILD_SHARED_LIBS  OFF CACHE BOOL "gk-server: static engine for a single-file install" FORCE)

# The engine's own install() rule would put the binary in the wheel's data
# directory; ours below places it inside the package instead.
set(GGUF_SERVER_INSTALL OFF CACHE BOOL "gk-server: install rules are ours" FORCE)

# Router mode (`--models`) spawns child servers via subprocess.h — harmless to
# keep and the GUI's custom-command box can use it.
gk_server_option(GK_SERVER_SUBPROCESS
    "Support router mode (the engine spawns child servers)" ON)
set(GGUF_SERVER_SUBPROCESS ${GK_SERVER_SUBPROCESS} CACHE BOOL "" FORCE)

# ── HTTPS / OpenSSL ──────────────────────────────────────────────────────────
# Off by default: OpenSSL is only needed to *download* models over HTTPS; the
# GUI always hands the engine local file paths, so the dependency buys nothing
# and costs portability (a foreign-ABI OpenSSL next to the toolchain breaks
# the build on Windows).
gk_server_option(GK_SERVER_OPENSSL
    "Link the engine against OpenSSL for HTTPS model downloads" OFF)
set(GGUF_SERVER_OPENSSL ${GK_SERVER_OPENSSL} CACHE BOOL "" FORCE)

# ── GPU / accelerator backends ───────────────────────────────────────────────
# One switch per backend drives the whole engine: the gk kernels evaluate the
# server's and the multimodal projectors' graphs alike. Anything else gk
# supports can still be passed straight through as -DGK_*.
#
# A CUDA build works its own architecture list out from nvcc and the installed
# GPUs, and embeds PTX for the newest, so an unlisted card JITs rather than
# failing. A wheel built on one machine for another should still say what it is
# targeting: -DGK_CUDA_ARCHITECTURES="75;86;89;120".
gk_server_option(GK_SERVER_CUDA   "Build the engine with the gk CUDA backend"   OFF)
gk_server_option(GK_SERVER_HIP    "Build the engine with the gk HIP backend"    OFF)
gk_server_option(GK_SERVER_VULKAN "Build the engine with the gk Vulkan backend" OFF)
if(APPLE)  # matches the engine's own default; APPLE is "" elsewhere, not a valid default
    set(_gk_metal_default ON)
else()
    set(_gk_metal_default OFF)
endif()
gk_server_option(GK_SERVER_METAL  "Build the engine with the gk Metal backend"  ${_gk_metal_default})

set(GGUF_SERVER_CUDA   ${GK_SERVER_CUDA}   CACHE BOOL "" FORCE)
set(GGUF_SERVER_HIP    ${GK_SERVER_HIP}    CACHE BOOL "" FORCE)
set(GGUF_SERVER_VULKAN ${GK_SERVER_VULKAN} CACHE BOOL "" FORCE)
set(GGUF_SERVER_METAL  ${GK_SERVER_METAL}  CACHE BOOL "" FORCE)

set(GK_SERVER_ENABLED_BACKENDS "")
foreach(backend IN ITEMS CUDA HIP VULKAN METAL)
    if(GK_SERVER_${backend})
        list(APPEND GK_SERVER_ENABLED_BACKENDS ${backend})
    endif()
endforeach()
if(GK_SERVER_ENABLED_BACKENDS)
    string(REPLACE ";" ", " _backend_list "${GK_SERVER_ENABLED_BACKENDS}")
    message(STATUS "gk-server: accelerator backends requested: ${_backend_list}")
else()
    message(STATUS "gk-server: CPU-only build (enable e.g. -DGK_SERVER_CUDA=ON for GPU)")
endif()

# ── Embedded web UI ──────────────────────────────────────────────────────────
# The engine embeds whatever static assets live in GGUF_SERVER_UI_DIR (default
# <engine>/ui/dist). The tree ships none, so the engine is API-only — mostly
# irrelevant here, because this package serves its own GUI.
if(NOT DEFINED CACHE{GGUF_SERVER_UI_DIR} AND DEFINED ENV{GGUF_SERVER_UI_DIR})
    set(GGUF_SERVER_UI_DIR "$ENV{GGUF_SERVER_UI_DIR}" CACHE PATH
        "directory with web UI assets to embed into the engine")
endif()

# EXCLUDE_FROM_ALL keeps every target the engine defines out of the default
# build — the dependency below pulls in the server binary and just the
# libraries it links against.
add_subdirectory("${GK_SERVER_ENGINE_DIR}" "${CMAKE_BINARY_DIR}/gk-server-engine" EXCLUDE_FROM_ALL)

if(NOT TARGET gguf-server)
    message(FATAL_ERROR "engine did not define the gguf-server target — is ${GK_SERVER_ENGINE_DIR} the gk-server engine source tree?")
endif()

add_custom_target(gk_server_engine ALL)
add_dependencies(gk_server_engine gguf-server)

# Install into the wheel (SKBUILD_PLATLIB_DIR) and also into the source tree
# so editable installs (`pip install -e .`) find the binary — the same dual
# install ggk and the gguf-* packages use.
install(
    PROGRAMS $<TARGET_FILE:gguf-server>
    DESTINATION "${CMAKE_CURRENT_SOURCE_DIR}/src/gk_server/bin"
)
if(DEFINED SKBUILD_PLATLIB_DIR)
    install(
        PROGRAMS $<TARGET_FILE:gguf-server>
        DESTINATION "${SKBUILD_PLATLIB_DIR}/gk_server/bin"
    )
endif()
