cmake_minimum_required(VERSION 4.0.0)
if(NOT DEFINED ECHOION_PRODUCT_VERSION)
    set(ECHOION_PRODUCT_VERSION 0.0.0)
endif()
if(NOT DEFINED ECHOION_COMPONENT_VERSION)
    set(ECHOION_COMPONENT_VERSION "${ECHOION_PRODUCT_VERSION}")
endif()
project(EchoionCore VERSION "${ECHOION_COMPONENT_VERSION}" LANGUAGES CXX)

if(PROJECT_IS_TOP_LEVEL)
    set(BUILD_SHARED_LIBS ON CACHE BOOL
        "Build shared component dependencies" FORCE)
    file(DOWNLOAD
        https://github.com/cpm-cmake/CPM.cmake/releases/download/v0.40.8/CPM.cmake
        "${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake"
        EXPECTED_HASH
            SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791)
    include("${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake")
    CPMAddPackage(
        NAME Void
        GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidlibrary.git
        GIT_TAG main
        OPTIONS "VOID_ENABLE_TESTING OFF")
    CPMAddPackage(
        NAME EchoionApi
        GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/echoionapi.git
        GIT_TAG main)
    option(BUILD_TESTS "Build component tests" ON)
    if(BUILD_TESTS)
        enable_testing()
    endif()
endif()

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
add_definitions(-DECHOION_API_EXPORT)
file(GLOB_RECURSE CORE_SOURCES
     CONFIGURE_DEPENDS
     "src/**.cpp"
)
add_library(EchoionCore SHARED ${CORE_SOURCES})
target_compile_definitions(EchoionCore PRIVATE
    ECHOION_CORE_VERSION="${ECHOION_COMPONENT_VERSION}"
    ECHOION_MODULE_BUILD
    ECHOION_COMPONENT_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
    ECHOION_COMPONENT_VERSION_MINOR=${PROJECT_VERSION_MINOR}
    ECHOION_COMPONENT_VERSION_PATCH=${PROJECT_VERSION_PATCH})

add_library(Echoion::Core ALIAS EchoionCore)

target_include_directories(EchoionCore PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../EchoionApi/include/echoion/api/config>
    $<INSTALL_INTERFACE:include>
)

# Core uses all API modules
target_link_libraries(EchoionCore PUBLIC 
    Echoion::ApiBase
    Echoion::ApiAudio
    Echoion::ApiTrack
    Echoion::ApiNetwork
    Echoion::ApiPlugin
    Echoion::ApiConfig
    Echoion::ApiRpc
    Echoion::ApiYouTube
    Echoion::ApiLogger
    Echoion::ApiEventBus
    Echoion::ApiDatabase
    Echoion::ApiOpaque
    Echoion::ApiPluginInterface
    Echoion::ApiCoreInterface
    Echoion::ApiUtils
    Echoion::ApiModuleAbi
)

find_package(PkgConfig REQUIRED)
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET
    libavformat>=59
    libavcodec>=59
    libswresample>=4
    libavutil>=57
)

CPMAddPackage(
    NAME quickjs
    GITHUB_REPOSITORY quickjs-ng/quickjs
    GIT_TAG v0.11.0
)

# quickjs-ng v0.11.0 compiles its C sources with -Werror, which trips newer GCC
# diagnostics (e.g. -Wmaybe-uninitialized / -Wdiscarded-qualifiers under GCC 16+).
# It is a vendored third-party dependency, so relax -Werror on every target it
# defines (qjs, qjsc, qjs-libc, ...) rather than guessing target names.
if(quickjs_SOURCE_DIR)
    get_property(_qjs_targets DIRECTORY "${quickjs_SOURCE_DIR}"
                 PROPERTY BUILDSYSTEM_TARGETS)
    foreach(_qjs_target ${_qjs_targets})
        get_target_property(_qjs_type ${_qjs_target} TYPE)
        if(NOT _qjs_type STREQUAL "INTERFACE_LIBRARY")
            target_compile_options(${_qjs_target} PRIVATE -Wno-error)
        endif()
    endforeach()
endif()

# Boost: the process must contain exactly ONE copy of the compiled Boost
# libraries. VoidLibrary links the SYSTEM Boost, so EchoionCore must use the
# same one — vendoring a second copy (the old AddBoost path fetched 1.90
# alongside the system 1.91) put two libboost_url.so versions into the
# process and the cross-bound symbols corrupted every parsed URL
# (SIGSEGV in boost::urls::url_view). Fall back to fetching only when no
# usable system Boost exists (in which case Void fetched the same one).
find_package(Boost 1.87 CONFIG QUIET COMPONENTS url thread container)
if(Boost_FOUND)
    message(STATUS "EchoionCore using system Boost ${Boost_VERSION}")
    # Distros ship CMake configs only for the compiled Boost libraries;
    # header-only components (asio, beast, uuid) have none. Map the targets
    # EchoionCore links onto the installed headers.
    foreach(_hdr asio beast uuid system)
        if(NOT TARGET Boost::${_hdr})
            add_library(_boost_${_hdr}_hdr INTERFACE)
            add_library(Boost::${_hdr} ALIAS _boost_${_hdr}_hdr)
            target_include_directories(_boost_${_hdr}_hdr INTERFACE
                                       "${Boost_INCLUDE_DIRS}")
        endif()
    endforeach()
else()
    set(AddBoost.cmake_VERSION 3.7.3)
    CPMAddPackage(
      NAME AddBoost.cmake
      VERSION "${AddBoost.cmake_VERSION}"
      URL "https://github.com/Arniiiii/AddBoost.cmake/archive/refs/tags/${AddBoost.cmake_VERSION}.tar.gz"
    )
    set(TRY_BOOST_VERSION "1.90.0")
    set(BOOST_MY_OPTIONS "BOOST_ENABLE_PYTHON ON;")
    set(BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "thread;system")
    set(BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "asio;beast;uuid;container;cobalt;url")

    add_boost(
      TRY_BOOST_VERSION BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED
      BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore
    )
endif()

find_package(Threads REQUIRED)
find_package(OpenSSL REQUIRED)
find_package(SQLite3 REQUIRED)
# FindSQLite3 exposed only SQLite::SQLite3 before CMake 4.3. Keep the
# component's preferred target name available across the supported CMake 4.x
# range; an alias created inside sibling VoidLibrary is not visible here.
if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3)
    add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
endif()
find_package(TBB REQUIRED)

target_link_libraries(EchoionCore
    PUBLIC
        PkgConfig::LIBAV
        TBB::tbb
        SQLite3::SQLite3
        # VoidLibrary modules (migration target — replacing in-house infra)
        Void::Data
        Void::Functional
        Void::System
        Void::Log
        Void::Async
        Void::Containers
        Void::Resilience
        Void::Text
        Void::Time
        Void::Math
        Void::Net
        Void::Sqlite
        Void::Service
        Void::ShortUrl
        Void::Plugin
    PRIVATE
        Threads::Threads
        qjs
        Boost::beast
        Boost::url
        Boost::asio
        OpenSSL::SSL
        OpenSSL::Crypto
)

if(MSVC)
    target_compile_options(EchoionCore PRIVATE /W4 /WX-)
    target_compile_definitions(EchoionCore PRIVATE _CRT_SECURE_NO_WARNINGS)
else()
    target_compile_options(EchoionCore PRIVATE -Wall -Wextra -Wpedantic)
endif()

if(BUILD_TESTS)
    include("${Void_SOURCE_DIR}/cmake/VoidTesting.cmake")

    add_executable(echoion_log_rotation_tests
        tests/test_log_rotation.cpp
        src/LogRotation.cpp
    )
    target_include_directories(echoion_log_rotation_tests PRIVATE
        "${CMAKE_CURRENT_SOURCE_DIR}/include"
    )
    target_compile_features(echoion_log_rotation_tests PRIVATE cxx_std_26)
    add_test(NAME echoion_log_rotation_tests
        COMMAND echoion_log_rotation_tests)
endif()

# Precompiled headers for the heavy translation units (MusicManager.cpp ~2.4k
# lines, Core.cpp, YouTubeClient.cpp). These pull in the same expensive standard
# and Void headers, so compiling them once cuts a large slice off build time.
# Disabled automatically under unity builds (CMake forbids combining the two).
option(ECHOION_ENABLE_PCH "Use precompiled headers for EchoionCore" ON)
if(ECHOION_ENABLE_PCH AND NOT CMAKE_UNITY_BUILD)
    target_precompile_headers(EchoionCore PRIVATE
        <string>
        <string_view>
        <vector>
        <memory>
        <optional>
        <chrono>
        <format>
        <mutex>
        <thread>
        <atomic>
        <functional>
    )
endif()

set_target_properties(EchoionCore PROPERTIES
    OUTPUT_NAME "Echoion"
    PREFIX ""
    SUFFIX ".ts"
    RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
    LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
    ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
)

# Export EchoionCore
target_include_directories(EchoionCore PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<INSTALL_INTERFACE:include>
)

install(TARGETS EchoionCore
    EXPORT EchoionCoreTargets
    RUNTIME DESTINATION bin
    LIBRARY DESTINATION lib
    ARCHIVE DESTINATION lib
    INCLUDES DESTINATION include
)

install(EXPORT EchoionCoreTargets
    FILE EchoionCoreTargets.cmake
    NAMESPACE Echoion::
    DESTINATION lib/cmake/EchoionCore
)

install(FILES abi/module.json
    DESTINATION share/echoion/components/EchoionCore/${PROJECT_VERSION}/abi)

# Package config files
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
    "${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfigVersion.cmake"
    VERSION ${PROJECT_VERSION}
    COMPATIBILITY SameMajorVersion
)

file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfig.cmake"
"include(\"\${CMAKE_CURRENT_LIST_DIR}/EchoionCoreTargets.cmake\")
include(CMakeFindDependencyMacro)
find_dependency(EchoionApi)
")

install(FILES
    "${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfig.cmake"
    "${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfigVersion.cmake"
    DESTINATION lib/cmake/EchoionCore
)

if(BUILD_TESTS)
	add_executable(echoion_core_config_loader_tests
		tests/test_config_loader.cpp)
	target_include_directories(echoion_core_config_loader_tests PRIVATE
		"${CMAKE_CURRENT_SOURCE_DIR}/include")
	target_link_libraries(echoion_core_config_loader_tests PRIVATE EchoionCore)
	add_test(NAME echoion_core_config_loader_tests
		COMMAND echoion_core_config_loader_tests)

	add_executable(echoion_core_extension_state_tests
		tests/test_extension_state.cpp)
	target_include_directories(echoion_core_extension_state_tests PRIVATE
		"${CMAKE_CURRENT_SOURCE_DIR}/include")
	target_link_libraries(echoion_core_extension_state_tests PRIVATE EchoionCore)
	add_test(NAME echoion_core_extension_state_tests
		COMMAND echoion_core_extension_state_tests)

	add_executable(echoion_core_teamspeak_directory_tests
		tests/test_teamspeak_directory.cpp
		src/TeamSpeakDirectoryService.cpp)
	target_include_directories(echoion_core_teamspeak_directory_tests PRIVATE
		"${CMAKE_CURRENT_SOURCE_DIR}/include")
	target_link_libraries(echoion_core_teamspeak_directory_tests PRIVATE EchoionCore)
	add_test(NAME echoion_core_teamspeak_directory_tests
		COMMAND echoion_core_teamspeak_directory_tests)

	add_executable(echoion_core_url_shortener_tests
		tests/test_url_shortener.cpp)
	target_include_directories(echoion_core_url_shortener_tests PRIVATE
		"${CMAKE_CURRENT_SOURCE_DIR}/include")
	target_link_libraries(echoion_core_url_shortener_tests PRIVATE EchoionCore)
	add_test(NAME echoion_core_url_shortener_tests
		COMMAND echoion_core_url_shortener_tests)

    add_executable(echoion_core_plugin_compatibility_tests
        tests/test_plugin_compatibility.cpp)
    target_include_directories(echoion_core_plugin_compatibility_tests PRIVATE
        "${CMAKE_CURRENT_SOURCE_DIR}/include"
        "${CMAKE_CURRENT_SOURCE_DIR}/src")
    target_link_libraries(echoion_core_plugin_compatibility_tests PRIVATE
        EchoionCore)
    void_add_tests(echoion_core_plugin_compatibility_tests)
endif()

option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF)
if(BUNDLE_FFMPEG)
    include(cmake/BundleFFmpeg.cmake)
    bundle_ffmpeg_libraries(EchoionCore)
endif()
