# Reproducible C++ build wiring for the Shard runtime protocol (DGR-002).
#
# Generates C++ message stubs from proto/shard_runtime.proto and builds the
# round-trip / cross-language compatibility test. Requires protoc and the
# protobuf C++ runtime. Works with either a CONFIG-mode protobuf install
# (protobuf::libprotobuf / protobuf::protoc targets, e.g. a from-source install
# on CMAKE_PREFIX_PATH) or CMake's bundled FindProtobuf module.
#
# The gRPC C++ service stubs are generated separately by scripts/generate_cpp.sh
# when grpc_cpp_plugin is present; the round-trip test needs only message
# serialization, so gRPC is intentionally not a build dependency here.
#
# Configure & build (out-of-tree):
#   cmake -S packages/node/native -B packages/node/native/build/cpp
#   cmake --build packages/node/native/build/cpp
# Run:
#   packages/node/native/build/cpp/shard_protocol_roundtrip_test --selftest

cmake_minimum_required(VERSION 3.16)
project(shard_runtime_protocol CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Prefer a CONFIG-mode protobuf (modern imported targets); fall back to the
# FindProtobuf module for system installs.
find_package(Protobuf CONFIG QUIET)
if(NOT Protobuf_FOUND)
  find_package(Protobuf REQUIRED)
endif()

if(TARGET protobuf::protoc)
  set(SHARD_PROTOC_EXECUTABLE "$<TARGET_FILE:protobuf::protoc>")
else()
  set(SHARD_PROTOC_EXECUTABLE "${Protobuf_PROTOC_EXECUTABLE}")
endif()

if(TARGET protobuf::libprotobuf)
  set(SHARD_PROTOBUF_LINK protobuf::libprotobuf)
else()
  set(SHARD_PROTOBUF_LINK ${Protobuf_LIBRARIES})
endif()

set(PROTO_DIR "${CMAKE_CURRENT_SOURCE_DIR}/proto")
set(PROTO_FILE "${PROTO_DIR}/shard_runtime.proto")
set(GEN_DIR "${CMAKE_CURRENT_BINARY_DIR}/gen")
file(MAKE_DIRECTORY "${GEN_DIR}")

set(PROTO_SRC "${GEN_DIR}/shard_runtime.pb.cc")
set(PROTO_HDR "${GEN_DIR}/shard_runtime.pb.h")

add_custom_command(
  OUTPUT "${PROTO_SRC}" "${PROTO_HDR}"
  COMMAND "${SHARD_PROTOC_EXECUTABLE}"
          "--proto_path=${PROTO_DIR}"
          "--cpp_out=${GEN_DIR}"
          "${PROTO_FILE}"
  DEPENDS "${PROTO_FILE}"
  COMMENT "Generating C++ protobuf stubs from shard_runtime.proto"
  VERBATIM)

add_executable(shard_protocol_roundtrip_test
  tests/roundtrip_test.cpp
  "${PROTO_SRC}")

target_include_directories(shard_protocol_roundtrip_test PRIVATE "${GEN_DIR}")
if(NOT TARGET protobuf::libprotobuf AND Protobuf_INCLUDE_DIRS)
  target_include_directories(shard_protocol_roundtrip_test PRIVATE
    ${Protobuf_INCLUDE_DIRS})
endif()

target_link_libraries(shard_protocol_roundtrip_test PRIVATE ${SHARD_PROTOBUF_LINK})

enable_testing()
add_test(NAME shard_protocol_roundtrip
         COMMAND shard_protocol_roundtrip_test --selftest)
