cmake_minimum_required(VERSION 4.0.0)
project(EchoionWeb VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

file(GLOB_RECURSE WEB_SOURCES CONFIGURE_DEPENDS "src/**.cpp")
add_library(EchoionWeb STATIC ${WEB_SOURCES})
add_library(Echoion::Web ALIAS EchoionWeb)

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
        Void::Data
        Void::Log
        Void::Async
    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 the built browser assets next to the runtime binary. Remove the target
# first so stale files (e.g. an earlier vanilla-JS build) never linger.
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"
)

install(DIRECTORY "${_web_dist}/" DESTINATION share/echoion/web)
