cmake_minimum_required(VERSION 3.22)
project(CxWebApp VERSION 1.0.0 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# ── Dependencies via FetchContent ─────────────────────────────
include(FetchContent)

# Asio (header-only, required by Crow)
FetchContent_Declare(
    asio
    GIT_REPOSITORY https://github.com/chriskohlhoff/asio.git
    GIT_TAG        asio-1-30-2
    GIT_SHALLOW    TRUE
)
FetchContent_MakeAvailable(asio)

# Tell Crow where to find Asio headers
set(ASIO_INCLUDE_DIR "${asio_SOURCE_DIR}/asio/include" CACHE PATH "" FORCE)

# Crow web framework
FetchContent_Declare(
    crow
    GIT_REPOSITORY https://github.com/CrowCpp/Crow.git
    GIT_TAG        v1.2.0
    GIT_SHALLOW    TRUE
)
FetchContent_MakeAvailable(crow)

# cpp-httplib (single-header HTTP/1.1 client used by the reverse-proxy routes)
FetchContent_Declare(
    cpphttplib
    GIT_REPOSITORY https://github.com/yhirose/cpp-httplib.git
    GIT_TAG        v0.18.0
    GIT_SHALLOW    TRUE
)
FetchContent_MakeAvailable(cpphttplib)

# ── Application ───────────────────────────────────────────────
add_executable(${PROJECT_NAME}
    src/main.cpp
    src/routes/api.cpp
    src/routes/pages.cpp
    src/routes/system.cpp
    src/routes/proxy.cpp
    src/routes/mac.cpp
)

target_compile_definitions(${PROJECT_NAME} PRIVATE
    CXWEBAPP_STATIC_DIR_DEFAULT="/opt/cxwebapp/share/CxWebApp/static"
)

target_include_directories(${PROJECT_NAME} PRIVATE
    ${CMAKE_SOURCE_DIR}/include
    ${asio_SOURCE_DIR}/asio/include
    ${cpphttplib_SOURCE_DIR}
)

target_link_libraries(${PROJECT_NAME} PRIVATE Crow::Crow)

# macOS: Link system frameworks
if(APPLE)
    find_library(COREFOUNDATION_LIBRARY CoreFoundation)
    find_library(SECURITY_LIBRARY Security)
    if(COREFOUNDATION_LIBRARY)
        target_link_libraries(${PROJECT_NAME} PRIVATE ${COREFOUNDATION_LIBRARY})
    endif()
    if(SECURITY_LIBRARY)
        target_link_libraries(${PROJECT_NAME} PRIVATE ${SECURITY_LIBRARY})
    endif()
endif()

# Copy static assets and templates to build directory
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_directory
        ${CMAKE_SOURCE_DIR}/static $<TARGET_FILE_DIR:${PROJECT_NAME}>/static
    COMMAND ${CMAKE_COMMAND} -E copy_directory
        ${CMAKE_SOURCE_DIR}/templates $<TARGET_FILE_DIR:${PROJECT_NAME}>/templates
    COMMENT "Copying static assets and templates"
)

# ── Install ───────────────────────────────────────────────────
install(TARGETS ${PROJECT_NAME} DESTINATION bin)
install(DIRECTORY static/ DESTINATION share/${PROJECT_NAME}/static)
install(DIRECTORY templates/ DESTINATION share/${PROJECT_NAME}/templates)
install(DIRECTORY share/cxai-mac/ DESTINATION share/cxai-mac)
