# Builds the gguf-server engine (the standalone C/C++ GGUF HTTP server) from
# the vendored source tree and installs the binary into the gguf_server
# package, where the Python backend spawns it. Modeled on gguf_diffusion's
# CMakeLists.txt.
#
# The engine tree carries its own kernels, runtime, common layer and HTTP
# server — there is no llama.cpp checkout and no external ggml. Adding it with
# EXCLUDE_FROM_ALL keeps its install() rules out of the wheel; the dependency
# below pulls in the one executable we ship.
cmake_minimum_required(VERSION 3.15)
project(gguf_server C CXX)

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

if(NOT GGUF_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(GGUF_SERVER_ENGINE_DIR "" CACHE PATH "Path to the gguf-server engine source tree")
if(NOT GGUF_SERVER_ENGINE_DIR AND DEFINED ENV{GGUF_SERVER_ENGINE_DIR})
    set(GGUF_SERVER_ENGINE_DIR "$ENV{GGUF_SERVER_ENGINE_DIR}")
endif()
if(NOT GGUF_SERVER_ENGINE_DIR)
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/vendor/server/CMakeLists.txt")
        set(GGUF_SERVER_ENGINE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/vendor/server")
    elseif(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../server/CMakeLists.txt")
        set(GGUF_SERVER_ENGINE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../server")
    endif()
endif()
if(NOT GGUF_SERVER_ENGINE_DIR OR NOT EXISTS "${GGUF_SERVER_ENGINE_DIR}/app/CMakeLists.txt")
    message(FATAL_ERROR
        "gguf-server engine source not found. Provide it via one of:\n"
        "  - a vendored copy at vendor/server (see scripts/vendor_engine.py)\n"
        "  - a sibling checkout at ../server\n"
        "  - -DGGUF_SERVER_ENGINE_DIR=/path/to/server or the same env var")
endif()
get_filename_component(GGUF_SERVER_ENGINE_DIR "${GGUF_SERVER_ENGINE_DIR}" ABSOLUTE)
message(STATUS "gguf-server: engine source at ${GGUF_SERVER_ENGINE_DIR}")

# ── Option helper ────────────────────────────────────────────────────────────
# The engine declares its own GGUF_SERVER_* options; declaring them here first
# wins, because option() leaves an existing cache entry alone. Values are read
# from the environment as well as -D, because `pip install` makes environment
# variables far easier to pass than CMake defines:
#   GGUF_SERVER_CUDA=1 pip install .
#   CMAKE_ARGS="-DGGUF_SERVER_CUDA=ON" pip install .
function(gguf_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 (common/common.h and kernels/include/ggml.h
    # both only define it "if not already defined", so their 0x0A00 never
    # applies). cpp-httplib then hard-errors with "doesn't support Windows 8 or
    # lower" and ::CreateFile2 goes undeclared, which takes down httplib.cpp,
    # download.cpp and hf-cache.cpp. 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 them in.
    gguf_server_option(GGUF_SERVER_MINGW_STATIC
        "Statically link the MinGW runtime into the engine binary" ON)
    if(GGUF_SERVER_MINGW_STATIC)
        add_link_options(-static-libgcc -static-libstdc++ -static)

        # ggml uses OpenMP, and CMake's FindOpenMP resolves it to
        # libgomp.dll.a — an explicit path to an *import* library, which
        # -static cannot override, leaving the binary needing libgomp-1.dll.
        # Point OpenMP at the static archive instead; if there isn't one,
        # drop OpenMP rather than ship a half-static binary (ggml falls back
        # to its own thread pool).
        if(NOT OpenMP_gomp_LIBRARY)
            set(_gguf_saved_suffixes ${CMAKE_FIND_LIBRARY_SUFFIXES})
            set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
            find_library(GGUF_SERVER_LIBGOMP_STATIC NAMES gomp)
            set(CMAKE_FIND_LIBRARY_SUFFIXES ${_gguf_saved_suffixes})
            if(GGUF_SERVER_LIBGOMP_STATIC)
                message(STATUS "gguf-server: static OpenMP runtime ${GGUF_SERVER_LIBGOMP_STATIC}")
                set(OpenMP_gomp_LIBRARY "${GGUF_SERVER_LIBGOMP_STATIC}"
                    CACHE FILEPATH "gguf-server: static OpenMP runtime" FORCE)
            else()
                message(STATUS "gguf-server: no static libgomp found, building without OpenMP")
                set(GGML_OPENMP OFF CACHE BOOL "gguf-server: keep the binary self-contained" FORCE)
            endif()
        endif()
    endif()
endif()

# ── Shape the engine build for a single-file wheel ───────────────────────────
# Static libs (ggml, 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 "gguf-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 "gguf-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.
gguf_server_option(GGUF_SERVER_SUBPROCESS
    "Support router mode (the engine spawns child servers)" ON)

# ── HTTPS / OpenSSL ──────────────────────────────────────────────────────────
# Off by default (the engine itself defaults it on). OpenSSL is only needed to
# *download* models over HTTPS (-hf / URL arguments); this package always hands
# the engine local file paths, so the dependency buys nothing and costs
# portability: find_package(OpenSSL) happily picks up a foreign-ABI install —
# an MSYS2 / MinGW libcrypto next to an MSVC toolchain puts MinGW headers on
# cl.exe's include path and breaks httplib.cpp, download.cpp and hf-cache.cpp
# with "winnt.h: fatal error C1189: No supported target architecture".
gguf_server_option(GGUF_SERVER_OPENSSL
    "Link the engine against OpenSSL for HTTPS model downloads" OFF)

# ── GPU / accelerator backends ───────────────────────────────────────────────
# These are the backends whose kernels the engine tree actually carries; each
# forwards to the ggml option of the same name. Anything else ggml supports can
# still be passed straight through as -DGGML_*.
gguf_server_option(GGUF_SERVER_CUDA   "Build the engine with the ggml CUDA backend"   OFF)
gguf_server_option(GGUF_SERVER_HIP    "Build the engine with the ggml HIP backend"    OFF)
gguf_server_option(GGUF_SERVER_VULKAN "Build the engine with the ggml Vulkan backend" OFF)
if(APPLE)  # matches the engine's own default; APPLE is "" elsewhere, not a valid default
    set(_gguf_metal_default ON)
else()
    set(_gguf_metal_default OFF)
endif()
gguf_server_option(GGUF_SERVER_METAL  "Build the engine with the ggml Metal backend"  ${_gguf_metal_default})

set(GGUF_SERVER_ENABLED_BACKENDS "")
foreach(backend IN ITEMS CUDA HIP VULKAN METAL)
    if(GGUF_SERVER_${backend})
        list(APPEND GGUF_SERVER_ENABLED_BACKENDS ${backend})
    endif()
endforeach()
if(GGUF_SERVER_ENABLED_BACKENDS)
    string(REPLACE ";" ", " _backend_list "${GGUF_SERVER_ENABLED_BACKENDS}")
    message(STATUS "gguf-server: accelerator backends requested: ${_backend_list}")
else()
    message(STATUS "gguf-server: CPU-only build (enable e.g. -DGGUF_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 and its own
# "/" returns 404 — irrelevant here, because this package serves its own GUI.
# Point the variable at a bundle if you want the engine's UI as well.
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("${GGUF_SERVER_ENGINE_DIR}" "${CMAKE_BINARY_DIR}/gguf-server-engine" EXCLUDE_FROM_ALL)

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

add_custom_target(gguf_server_engine ALL)
add_dependencies(gguf_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 gguf_diffusion and gguf_editor use.
install(
    PROGRAMS $<TARGET_FILE:gguf-server>
    DESTINATION "${CMAKE_CURRENT_SOURCE_DIR}/src/gguf_server/bin"
)
if(DEFINED SKBUILD_PLATLIB_DIR)
    install(
        PROGRAMS $<TARGET_FILE:gguf-server>
        DESTINATION "${SKBUILD_PLATLIB_DIR}/gguf_server/bin"
    )
endif()
