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(EchoionWeb VERSION "${ECHOION_COMPONENT_VERSION}" LANGUAGES CXX)
include(GNUInstallDirs)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

if(PROJECT_IS_TOP_LEVEL)
    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()

file(GLOB_RECURSE WEB_SOURCES CONFIGURE_DEPENDS "src/**.cpp")
add_library(EchoionWeb SHARED ${WEB_SOURCES})
add_library(Echoion::Web ALIAS EchoionWeb)
target_compile_definitions(EchoionWeb PRIVATE
    ECHOION_MODULE_BUILD
    ECHOION_COMPONENT_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
    ECHOION_COMPONENT_VERSION_MINOR=${PROJECT_VERSION_MINOR}
    ECHOION_COMPONENT_VERSION_PATCH=${PROJECT_VERSION_PATCH})
set_target_properties(EchoionWeb PROPERTIES
    EXPORT_NAME Web
    OUTPUT_NAME echoion-web
    VERSION "${PROJECT_VERSION}"
    SOVERSION "${PROJECT_VERSION_MAJOR}")

target_include_directories(EchoionWeb PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<INSTALL_INTERFACE:include>
)

# EchoionCore is configured before this module and creates the header-only
# Boost:: targets from the single system Boost. Fall back to discovering them
# only if this module is ever built without Core. Check each target because
# aliases created by a sibling directory are not necessarily visible here.
find_package(Boost 1.87 CONFIG QUIET COMPONENTS system url)
foreach(_hdr asio beast system)
    if(NOT TARGET Boost::${_hdr})
        add_library(_web_boost_${_hdr}_hdr INTERFACE)
        add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr)
        target_include_directories(_web_boost_${_hdr}_hdr INTERFACE
                                   "${Boost_INCLUDE_DIRS}")
    endif()
endforeach()

find_package(Threads REQUIRED)

target_link_libraries(EchoionWeb
    PUBLIC
        Echoion::ApiConfig
        Echoion::ApiModuleAbi
        Void::Data
        Void::Log
        Void::Async
        Void::Resilience
    PRIVATE
        Threads::Threads
        Boost::beast
        Boost::asio
        Boost::system
        Boost::url
)

if(MSVC)
    target_compile_options(EchoionWeb PRIVATE /W4 /WX-)
else()
    target_compile_options(EchoionWeb PRIVATE -Wall -Wextra -Wpedantic)
endif()

# ── Browser frontend (Vite + React + TypeScript) ─────────────────────────────
# The UI lives in frontend/ and is built with npm/vite into frontend/web-dist.
# That build output is what ships next to the runtime binary (default webRoot
# "./web", relative to the working directory) and is installed. Opt out with
# -DECHOION_BUILD_WEB=OFF to skip the npm build (e.g. for a C++-only CI job).
if(BUILD_TESTS)
    add_executable(echoion_web_security_tests
        tests/HttpSecurityTests.cpp)
    target_link_libraries(echoion_web_security_tests PRIVATE
        EchoionWeb
        Threads::Threads)
    add_test(NAME echoion_web_security_tests
        COMMAND echoion_web_security_tests)
endif()

option(ECHOION_BUILD_WEB "Build the React dashboard frontend with npm/vite" ON)

set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend")
set(_web_dist "${_web_frontend}/web-dist")

if(ECHOION_BUILD_WEB)
    find_program(NPM_EXECUTABLE NAMES npm npm.cmd)
    if(NOT NPM_EXECUTABLE)
        message(FATAL_ERROR
            "npm was not found but ECHOION_BUILD_WEB is ON. Install Node.js/npm, "
            "or configure with -DECHOION_BUILD_WEB=OFF to skip the web frontend.")
    endif()

    # Rebuild web-dist whenever any source/config under frontend/ (excluding
    # node_modules and the output dir) changes. CONFIGURE_DEPENDS re-globs at
    # build time so new files are picked up without re-running CMake.
    file(GLOB_RECURSE _web_tree_srcs CONFIGURE_DEPENDS
        LIST_DIRECTORIES FALSE
        "${_web_frontend}/src/*"
        "${_web_frontend}/public/*")
    set(_web_srcs
        ${_web_tree_srcs}
        "${_web_frontend}/index.html"
        "${_web_frontend}/package.json"
        "${_web_frontend}/package-lock.json"
        "${_web_frontend}/tsconfig.json"
        "${_web_frontend}/vite.config.ts")

    add_custom_command(
        OUTPUT "${_web_dist}/index.html"
        # Release builds run `npm ci` before CMake. This lockfile-aware fallback
        # keeps direct developer builds convenient without reinstalling on every
        # incremental build.
        COMMAND ${NPM_EXECUTABLE} install --prefer-offline --no-audit --no-fund
        COMMAND ${NPM_EXECUTABLE} run build
        WORKING_DIRECTORY "${_web_frontend}"
        DEPENDS ${_web_srcs}
        COMMENT "Building Echoion web frontend (vite)"
        VERBATIM)
    add_custom_target(EchoionWebFrontend ALL
        DEPENDS "${_web_dist}/index.html")
    add_dependencies(EchoionWeb EchoionWebFrontend)

    set(_web_assets "${_web_dist}")
else()
    # Frontend build skipped: ship whatever is already in web-dist (a prior
    # build or a committed snapshot). Falls back to nothing if absent.
    set(_web_assets "${_web_dist}")
endif()

# Ship generated assets, or an explicitly supplied existing snapshot. A
# C++-only component build with ECHOION_BUILD_WEB=OFF must not require a stale
# web-dist directory.
if(ECHOION_BUILD_WEB OR EXISTS "${_web_dist}/index.html")
    add_custom_command(TARGET EchoionWeb POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E rm -rf "${CMAKE_BINARY_DIR}/bin/web"
        COMMAND ${CMAKE_COMMAND} -E copy_directory
            "${_web_assets}"
            "${CMAKE_BINARY_DIR}/bin/web"
        COMMENT "Copying EchoionWeb static assets to bin/web")
endif()

install(TARGETS EchoionWeb
    EXPORT EchoionWebTargets
    LIBRARY DESTINATION
        "${CMAKE_INSTALL_LIBDIR}/echoion/components/EchoionWeb/${PROJECT_VERSION}/lib"
    RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
    ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
    INCLUDES DESTINATION include)
install(DIRECTORY include/ DESTINATION include)
install(FILES abi/module.json
    DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/components/EchoionWeb/${PROJECT_VERSION}/abi")
install(EXPORT EchoionWebTargets
    FILE EchoionWebTargets.cmake
    NAMESPACE Echoion::
    DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/EchoionWeb")
if(ECHOION_BUILD_WEB OR EXISTS "${_web_dist}/index.html")
    install(DIRECTORY "${_web_dist}/"
        DESTINATION
            "${CMAKE_INSTALL_DATADIR}/echoion/components/EchoionWeb/${PROJECT_VERSION}/web")
endif()
