cmake_minimum_required(VERSION 3.16)
project(synor_sdk VERSION 0.1.0 LANGUAGES C)

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)

# Options
option(BUILD_SHARED_LIBS "Build shared library" ON)
option(BUILD_TESTS "Build tests" ON)
option(BUILD_EXAMPLES "Build examples" ON)

# Find dependencies
find_package(CURL REQUIRED)
find_package(PkgConfig QUIET)
if(PkgConfig_FOUND)
    pkg_check_modules(JANSSON jansson)
endif()

# If jansson not found via pkg-config, try find_library
if(NOT JANSSON_FOUND)
    find_library(JANSSON_LIBRARIES jansson)
    find_path(JANSSON_INCLUDE_DIRS jansson.h)
    if(JANSSON_LIBRARIES AND JANSSON_INCLUDE_DIRS)
        set(JANSSON_FOUND TRUE)
    endif()
endif()

if(NOT JANSSON_FOUND)
    message(WARNING "jansson library not found. Using bundled JSON parser.")
    set(USE_BUNDLED_JSON TRUE)
endif()

# Library sources
set(SYNOR_SOURCES
    src/synor_compute.c
    src/common.c
    src/wallet/wallet.c
    src/rpc/rpc.c
    src/storage/storage.c
)

# Create library
add_library(synor_sdk ${SYNOR_SOURCES})

target_include_directories(synor_sdk
    PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        $<INSTALL_INTERFACE:include>
    PRIVATE
        ${JANSSON_INCLUDE_DIRS}
)

target_link_libraries(synor_sdk
    PRIVATE
        CURL::libcurl
        m
)

if(JANSSON_FOUND)
    target_link_libraries(synor_sdk PRIVATE ${JANSSON_LIBRARIES})
    target_compile_definitions(synor_sdk PRIVATE HAVE_JANSSON)
endif()

# Platform-specific settings
if(WIN32)
    target_link_libraries(synor_sdk PRIVATE ws2_32)
endif()

# Set library properties
set_target_properties(synor_sdk PROPERTIES
    VERSION ${PROJECT_VERSION}
    SOVERSION ${PROJECT_VERSION_MAJOR}
)

# Installation
include(GNUInstallDirs)

install(TARGETS synor_sdk
    EXPORT synor_sdk-targets
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)

install(DIRECTORY include/
    DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)

install(EXPORT synor_sdk-targets
    FILE synor_sdk-targets.cmake
    NAMESPACE synor::
    DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/synor_sdk
)

# Alias for backwards compatibility
add_library(synor_compute ALIAS synor_sdk)

# Tests
if(BUILD_TESTS)
    enable_testing()
    add_subdirectory(tests EXCLUDE_FROM_ALL)
endif()

# Examples
if(BUILD_EXAMPLES)
    add_subdirectory(examples EXCLUDE_FROM_ALL)
endif()
