cmake_minimum_required(VERSION 3.20)
project(PhorcysDotsTtsBridge C)

if(NOT DEFINED LLAMA_CPP_ROOT)
  message(FATAL_ERROR "LLAMA_CPP_ROOT is required")
endif()

if(NOT DEFINED BRIDGE_SOURCE)
  message(FATAL_ERROR "BRIDGE_SOURCE is required")
endif()

# Windows paths must be passed with forward slashes. Backslashes in -D values are
# parsed by CMake language code as string escapes after variable expansion.
# The setup scripts normalize these values before invoking CMake; keep this guard
# to fail with an actionable message if a caller invokes this CMake project directly.
if(LLAMA_CPP_ROOT MATCHES [[\\]] OR BRIDGE_SOURCE MATCHES [[\\]])
  message(FATAL_ERROR "LLAMA_CPP_ROOT and BRIDGE_SOURCE must use forward slashes, not Windows backslashes.")
endif()

if(NOT EXISTS "${BRIDGE_SOURCE}")
  message(FATAL_ERROR "BRIDGE_SOURCE does not exist: ${BRIDGE_SOURCE}")
endif()

find_path(LLAMA_INCLUDE_DIR llama.h
  PATHS
    "${LLAMA_CPP_ROOT}/include"
  REQUIRED)

find_path(GGML_INCLUDE_DIR ggml.h
  PATHS
    "${LLAMA_CPP_ROOT}/ggml/include"
    "${LLAMA_CPP_ROOT}/include"
  REQUIRED)

find_library(LLAMA_LIBRARY
  NAMES llama libllama
  PATHS
    "${LLAMA_CPP_ROOT}/build/bin"
    "${LLAMA_CPP_ROOT}/build/bin/Release"
    "${LLAMA_CPP_ROOT}/build/lib"
    "${LLAMA_CPP_ROOT}/build/src"
    "${LLAMA_CPP_ROOT}/build"
  REQUIRED)

add_library(backbone_bridge SHARED "${BRIDGE_SOURCE}")
target_include_directories(backbone_bridge PRIVATE "${LLAMA_INCLUDE_DIR}" "${GGML_INCLUDE_DIR}")
target_link_libraries(backbone_bridge PRIVATE "${LLAMA_LIBRARY}")

if(MSVC)
  target_compile_options(backbone_bridge PRIVATE /O2)
else()
  target_compile_options(backbone_bridge PRIVATE -O2 -fPIC)
endif()

set_target_properties(backbone_bridge PROPERTIES OUTPUT_NAME "backbone_bridge")

if(NOT WIN32)
  set_target_properties(backbone_bridge PROPERTIES
    BUILD_RPATH "\$ORIGIN"
    INSTALL_RPATH "\$ORIGIN")
endif()