# Protocol Buffers and gRPC service definitions
# Uses system-installed protobuf and gRPC packages

# Proto files directory
set(PROTO_DIR ${CMAKE_CURRENT_SOURCE_DIR}/proto)

# Generated files directory
set(PROTO_GEN_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated)
file(MAKE_DIRECTORY ${PROTO_GEN_DIR})

# Proto source files
set(PROTO_FILES
    ${PROTO_DIR}/crm.proto
    ${PROTO_DIR}/database.proto
    ${PROTO_DIR}/llm.proto
)

# Generate C++ sources from proto files
set(PROTO_SRCS)
set(PROTO_HDRS)
set(GRPC_SRCS)
set(GRPC_HDRS)

foreach(PROTO_FILE ${PROTO_FILES})
    get_filename_component(PROTO_NAME ${PROTO_FILE} NAME_WE)

    list(APPEND PROTO_SRCS "${PROTO_GEN_DIR}/${PROTO_NAME}.pb.cc")
    list(APPEND PROTO_HDRS "${PROTO_GEN_DIR}/${PROTO_NAME}.pb.h")
    list(APPEND GRPC_SRCS "${PROTO_GEN_DIR}/${PROTO_NAME}.grpc.pb.cc")
    list(APPEND GRPC_HDRS "${PROTO_GEN_DIR}/${PROTO_NAME}.grpc.pb.h")

    add_custom_command(
        OUTPUT
            "${PROTO_GEN_DIR}/${PROTO_NAME}.pb.cc"
            "${PROTO_GEN_DIR}/${PROTO_NAME}.pb.h"
            "${PROTO_GEN_DIR}/${PROTO_NAME}.grpc.pb.cc"
            "${PROTO_GEN_DIR}/${PROTO_NAME}.grpc.pb.h"
        COMMAND ${PROTOC_EXECUTABLE}
            --cpp_out=${PROTO_GEN_DIR}
            --grpc_out=${PROTO_GEN_DIR}
            --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN}
            -I${PROTO_DIR}
            ${PROTO_FILE}
        DEPENDS ${PROTO_FILE}
        COMMENT "Generating protobuf/gRPC sources for ${PROTO_NAME}"
    )
endforeach()

# Proto library
add_library(smartbotic_proto STATIC
    ${PROTO_SRCS}
    ${GRPC_SRCS}
)

target_include_directories(smartbotic_proto
    PUBLIC
        ${PROTO_GEN_DIR}
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
)

# Link against system gRPC and protobuf
target_link_libraries(smartbotic_proto
    PUBLIC
        PkgConfig::GRPC
        grpc_reflection
        protobuf::libprotobuf
)

add_library(smartbotic::proto ALIAS smartbotic_proto)
