cmake_minimum_required(VERSION 3.28)
file(STRINGS "native/PKIPC.version" PKIPC_VERSION_TAG LIMIT_COUNT 1)
string(STRIP "${PKIPC_VERSION_TAG}" PKIPC_VERSION_TAG)
if(NOT PKIPC_VERSION_TAG MATCHES "^v([0-9]+\\.[0-9]+\\.[0-9]+)$")
    message(FATAL_ERROR "native/PKIPC.version must contain v<major>.<minor>.<patch>")
endif()
project(PKIPC VERSION "${CMAKE_MATCH_1}" LANGUAGES C CXX)
if(DEFINED SKBUILD_PROJECT_VERSION AND NOT PROJECT_VERSION STREQUAL SKBUILD_PROJECT_VERSION)
    message(FATAL_ERROR "Python and C++ SDK versions disagree")
endif()

find_package(Python REQUIRED COMPONENTS Interpreter Development.Module)
find_package(pybind11 3 CONFIG REQUIRED)
include(FetchContent)
set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)
set(LIBUV_BUILD_SHARED OFF)
set(LIBUV_BUILD_TESTS OFF)
set(LIBUV_BUILD_BENCH OFF)
FetchContent_Declare(libuv
    URL "${CMAKE_CURRENT_SOURCE_DIR}/native/libuv-v1.51.0.tar.gz"
    URL_HASH "SHA256=5f0557b90b1106de71951a3c3931de5e0430d78da1d9a10287ebc7a3f78ef8eb"
    EXCLUDE_FROM_ALL)
FetchContent_MakeAvailable(libuv)
set_target_properties(uv_a PROPERTIES POSITION_INDEPENDENT_CODE ON)

pybind11_add_module(_native MODULE native/bindings.cpp native/src/Channel.cpp)
target_compile_features(_native PRIVATE cxx_std_17)
target_compile_definitions(_native PRIVATE PKIPC_BUILDING_LIBRARY)
target_include_directories(_native PRIVATE native/include)
target_link_libraries(_native PRIVATE uv_a)
if(WIN32)
    target_compile_definitions(_native PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
endif()
if(MSVC)
    target_compile_options(_native PRIVATE /W4 /permissive- /utf-8 /EHsc
        /external:anglebrackets /external:W0)
else()
    target_compile_options(_native PRIVATE -Wall -Wextra -Wpedantic)
endif()
install(TARGETS _native LIBRARY DESTINATION pkipc RUNTIME DESTINATION pkipc)
