# Phase 0 WASM hello-world.
#
# Only built when the Emscripten toolchain is active (see the root
# CMakeLists.txt — it early-returns into this subdir when EMSCRIPTEN is set).
# Rule R5: this target must never become a Phase 1 dependency.

if(NOT EMSCRIPTEN)
    message(FATAL_ERROR
        "wasm/CMakeLists.txt requires the Emscripten toolchain. "
        "Use: cmake --preset wasm  (after activating emsdk).")
endif()

add_executable(hello hello.cpp)

# Emit an ES6 module so Node 20+ and modern browsers can `import` it directly.
# Suffix .mjs is what tells emcc to emit an ES module; the matching .wasm is
# produced alongside it.
set_target_properties(hello PROPERTIES
    OUTPUT_NAME "hello"
    SUFFIX ".mjs"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)

# Emscripten link flags. Keep this list short — every flag added here is a
# Phase 0 commitment the frontend dev will inherit.
target_link_options(hello PRIVATE
    "-sMODULARIZE=1"
    "-sEXPORT_ES6=1"
    "-sENVIRONMENT=node,web"
    # Functions callable from JS via ccall/cwrap. Underscore-prefix is the
    # C symbol name emscripten exposes.
    "-sEXPORTED_FUNCTIONS=['_add','_hello_version']"
    "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap']"
    # Engine blueprint §6.3: real PDFs can exceed the default heap.
    "-sALLOW_MEMORY_GROWTH=1"
)

target_compile_features(hello PRIVATE cxx_std_23)

message(STATUS "WASM hello-world configured")
message(STATUS "  Output ............... ${CMAKE_BINARY_DIR}/bin/hello.mjs (+ hello.wasm)")

# Phase 1/2 WASM Engine target
add_executable(pdfengine_wasm
    bindings/wasm_engine.cpp
)

set_target_properties(pdfengine_wasm PROPERTIES
    OUTPUT_NAME "pdfengine"
    SUFFIX ".mjs"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)

target_include_directories(pdfengine_wasm PRIVATE
    "${CMAKE_CURRENT_SOURCE_DIR}/bindings"
)

target_link_libraries(pdfengine_wasm PRIVATE pdfengine::pdfengine)

target_link_options(pdfengine_wasm PRIVATE
    "-sMODULARIZE=1"
    "-sEXPORT_ES6=1"
    "-sENVIRONMENT=node,web"
    "-sALLOW_MEMORY_GROWTH=1"
    "-sWASM_BIGINT"                 # PDFium uses i64
    "-sSTACK_SIZE=5MB"              # PDFium render is stack-heavy
    "-sEXPORTED_FUNCTIONS=['_loadDocument','_pageCount','_renderPagePng','_previewRender','_lastRenderPtr','_lastRenderW','_lastRenderH','_lastLayoutJson','_freeDocument','_engineBuildInfo','_malloc','_free']"
    "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','getValue','setValue','HEAPU8']"
)

target_compile_features(pdfengine_wasm PRIVATE cxx_std_23)

message(STATUS "WASM pdfengine configured")
message(STATUS "  Output ............... ${CMAKE_BINARY_DIR}/bin/pdfengine.mjs (+ pdfengine.wasm)")
