cmake_minimum_required(VERSION 4.0.0)
project(Echoion VERSION 1.0.0 LANGUAGES CXX)

# Default to a Release build when the developer/CI did not pick a config.
# Without this, single-config generators leave CMAKE_BUILD_TYPE empty and GCC
# falls back to -O0, so "production" builds shipped unoptimised. Set this before
# any CPMAddPackage() below so fetched dependencies (Void, Boost, quickjs) are
# compiled with the same optimisation level as Echoion itself.
get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(NOT _isMultiConfig AND NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
    set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
        Debug Release RelWithDebInfo MinSizeRel)
    message(STATUS "No CMAKE_BUILD_TYPE set; defaulting to Release")
endif()

# Use ccache (or sccache) as a compiler launcher when available to speed up
# incremental and clean-from-cache rebuilds. Opt-out with -DECHOION_USE_CCACHE=OFF.
option(ECHOION_USE_CCACHE "Use ccache/sccache compiler launcher if found" ON)
if(ECHOION_USE_CCACHE AND NOT CMAKE_CXX_COMPILER_LAUNCHER)
    find_program(ECHOION_CCACHE_PROGRAM NAMES ccache sccache)
    if(ECHOION_CCACHE_PROGRAM)
        set(CMAKE_C_COMPILER_LAUNCHER "${ECHOION_CCACHE_PROGRAM}")
        set(CMAKE_CXX_COMPILER_LAUNCHER "${ECHOION_CCACHE_PROGRAM}")
        message(STATUS "Compiler cache enabled: ${ECHOION_CCACHE_PROGRAM}")
    endif()
endif()

# Include CPM
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)

# Include PackageProject.cmake
CPMAddPackage(
    NAME PackageProject.cmake
    GITHUB_REPOSITORY TheLartians/PackageProject.cmake
    VERSION 1.11.2
)

# VoidLibrary — modular C++26 infrastructure (Json, Logging, Configuration,
# Plugin, Service, Async, Functional, System, Fsm, ...). Echoion's in-house
# infrastructure is migrated onto these Void:: targets.
# For local development against a working copy, configure with
#   -DCPM_Void_SOURCE=/path/to/VoidLibrary
# which CPM honours over the git checkout below.
CPMAddPackage(
    NAME Void
    GIT_REPOSITORY http://git.faumaray.ru/void/voidlibrary.git
    GIT_TAG main
    OPTIONS
        "VOID_ENABLE_TESTING OFF"
)

set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc")
set(CXX_SCAN_FOR_MODULES OFF)
# GCC 16+ exposes experimental C++26 reflection (P2996) via -freflection.
# Void's header-only INTERFACE modules (Data/Functional/Core) do not propagate
# this flag, so apply it tree-wide for every echoion target that may include
# <Void/Data/Reflect.hpp>, <Void/Configuration/Bind.hpp>, etc.
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
    # Guard to C++ only — vendored C dependencies (quickjs) must not see it.
    add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-freflection>)
endif()

# Link-time optimisation for Release configs only (keeps Debug builds fast).
# Experimental C++26 reflection (-freflection) is a front-end feature and is
# orthogonal to GCC's LTO, but gate behind an option so it can be disabled if a
# given toolchain rejects the combination.
option(ECHOION_ENABLE_LTO "Enable interprocedural optimisation for Release builds" ON)
if(ECHOION_ENABLE_LTO)
    include(CheckIPOSupported)
    check_ipo_supported(RESULT _ipoSupported OUTPUT _ipoError LANGUAGES CXX)
    if(_ipoSupported)
        set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE ON)
        set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO ON)
        message(STATUS "Interprocedural optimisation (LTO) enabled for Release")
    else()
        message(STATUS "IPO/LTO not supported by toolchain: ${_ipoError}")
    endif()
endif()

# Unity builds batch translation units to cut compile time. Kept OFF by default
# because reflection TUs and Glaze-heavy headers can blow up unity batch memory;
# enable per-machine with -DECHOION_UNITY_BUILD=ON.
option(ECHOION_UNITY_BUILD "Enable CMake unity (jumbo) builds" OFF)
if(ECHOION_UNITY_BUILD)
    set(CMAKE_UNITY_BUILD ON)
    set(CMAKE_UNITY_BUILD_BATCH_SIZE 8)
    message(STATUS "Unity build enabled (batch size 8)")
endif()

# Enable folder organization in IDEs
set_property(GLOBAL PROPERTY USE_FOLDERS ON)

# Options
option(BUILD_API "Build EchoionApi" ON)
option(BUILD_CORE "Build EchoionCore" ON)
option(BUILD_PLUGIN "Build EchoionPlugin" ON)
option(BUILD_DESKTOP "Build EchoionDesktop" ON)
option(BUILD_WEB "Build EchoionWeb (browser interface + sync-watch)" ON)
option(BUILD_TESTS "Build tests" OFF)
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
option(ECHOION_STATIC_LINK "Statically link dependencies for standalone distribution" ON)

# Static linking configuration
if(ECHOION_STATIC_LINK)
    set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE)
    set(BUILD_SHARED_LIBS OFF)
    message(STATUS "Static linking enabled - building standalone distribution")
endif()

# Find packages
find_package(Threads REQUIRED)

# Add subdirectories
if(BUILD_API)
    add_subdirectory(EchoionApi)
endif()

if(BUILD_CORE)
    add_subdirectory(EchoionCore)
endif()

# EchoionWeb is added after Core so it can reuse the single Boost header
# targets Core discovers. Core owns and starts the web server, so link them
# here (both targets now exist) and flag Core so the wiring compiles in.
if(BUILD_WEB AND BUILD_CORE)
    add_subdirectory(EchoionWeb)
    if(TARGET EchoionCore AND TARGET EchoionWeb)
        target_link_libraries(EchoionCore PRIVATE EchoionWeb)
        target_compile_definitions(EchoionCore PRIVATE ECHOION_WITH_WEB)
    endif()
endif()

if(BUILD_PLUGIN)
    add_subdirectory(EchoionPlugin)
endif()

if(BUILD_DESKTOP)
    add_subdirectory(EchoionDesktop)
endif()

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

# Packaging configuration
include(CPack)
set(CPACK_PACKAGE_NAME "Echoion")
set(CPACK_PACKAGE_VENDOR "Echoion")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak")
set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR})
set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR})
set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH})
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")

# Platform-specific packaging
if(WIN32)
    set(CPACK_GENERATOR "ZIP;NSIS")
    set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot")
    set(CPACK_NSIS_HELP_LINK "https://github.com/yourusername/echoion")
    set(CPACK_NSIS_URL_INFO_ABOUT "https://github.com/yourusername/echoion")
elseif(APPLE)
    set(CPACK_GENERATOR "DragNDMGZ")
    set(CPACK_DMG_VOLUME_NAME "Echoion")
else()
    set(CPACK_GENERATOR "TGZ;DEB;RPM")
    set(CPACK_DEBIAN_PACKAGE_DEPENDS "libssl3, libavformat58, libavcodec58, libsqlite3-0")
    set(CPACK_RPM_PACKAGE_REQUIRES "openssl, ffmpeg-libs, sqlite")
endif()

# Bundling and deployment helpers
include(GNUInstallDirs)

# Function to bundle Qt dependencies
function(bundle_qt_dependencies target)
    if(NOT TARGET ${target})
        return()
    endif()
    
    if(WIN32)
        find_program(WINDEPLOYQT windeployqt HINTS ${Qt6Core_DIR}/../../../bin)
        if(WINDEPLOYQT)
            add_custom_command(TARGET ${target} POST_BUILD
                COMMAND ${WINDEPLOYQT} 
                    --dir $<TARGET_FILE_DIR:${target}>/qt_libs
                    --release
                    --no-translations
                    --no-compiler-runtime
                    --no-opengl-sw
                    $<TARGET_FILE:${target}>
                COMMENT "Bundling Qt dependencies for ${target}"
            )
        endif()
    elseif(APPLE)
        find_program(MACDEPLOYQT macdeployqt HINTS ${Qt6Core_DIR}/../../../bin)
        if(MACDEPLOYQT)
            add_custom_command(TARGET ${target} POST_BUILD
                COMMAND ${MACDEPLOYQT} $<TARGET_FILE:${target}> -always-overwrite
                COMMENT "Bundling Qt dependencies for ${target}"
            )
        endif()
    endif()
endfunction()

# Function to install target with its dependencies
function(install_with_dependencies target)
    if(NOT TARGET ${target})
        return()
    endif()
    
    get_target_property(target_type ${target} TYPE)
    
    if(target_type STREQUAL "EXECUTABLE")
        install(TARGETS ${target}
            RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
            BUNDLE DESTINATION ${CMAKE_INSTALL_BINDIR}
        )
        
        # Bundle Qt if needed
        get_target_property(linked_libs ${target} LINK_LIBRARIES)
        if(linked_libs)
            foreach(lib ${linked_libs})
                if(lib MATCHES "Qt6::")
                    bundle_qt_dependencies(${target})
                    break()
                endif()
            endforeach()
        endif()
    elseif(target_type STREQUAL "SHARED_LIBRARY")
        install(TARGETS ${target}
            RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
            LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
            ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
        )
    endif()
endfunction()

# Apply bundling to targets after all subdirectories are added
if(BUILD_DESKTOP AND TARGET EchoionDesktop)
    install_with_dependencies(EchoionDesktop)
endif()

if(BUILD_CORE AND TARGET EchoionCore)
    install_with_dependencies(EchoionCore)
endif()

if(BUILD_PLUGIN AND TARGET EchoionPlugin)
    install_with_dependencies(EchoionPlugin)
endif()

# Print configuration summary
message(STATUS "")
message(STATUS "Echoion Configuration:")
message(STATUS "  Version: ${PROJECT_VERSION}")
message(STATUS "  C++ Standard: ${CMAKE_CXX_STANDARD}")
message(STATUS "  Build API: ${BUILD_API}")
message(STATUS "  Build Core: ${BUILD_CORE}")
message(STATUS "  Build Plugin: ${BUILD_PLUGIN}")
message(STATUS "  Build Desktop: ${BUILD_DESKTOP}")
message(STATUS "  Build Tests: ${BUILD_TESTS}")
message(STATUS "  Static Link: ${ECHOION_STATIC_LINK}")
message(STATUS "")
message(STATUS "Install prefix: ${CMAKE_INSTALL_PREFIX}")
message(STATUS "To build: cmake --build build")
message(STATUS "To install: cmake --install build --prefix <install_dir>")
message(STATUS "To package: cpack -G TGZ (or DEB, RPM, ZIP, NSIS)")
message(STATUS "")
