# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

  if (onnxruntime_MINIMAL_BUILD AND NOT onnxruntime_EXTENDED_MINIMAL_BUILD)
    message(FATAL_ERROR "WebGPU EP can not be used in a basic minimal build. Please build with '--minimal_build extended'")
  endif()

  add_compile_definitions(USE_WEBGPU=1)

  if (onnxruntime_ENABLE_WEBASSEMBLY_THREADS)
    add_definitions(-DENABLE_WEBASSEMBLY_THREADS=1)
  endif()

  file(GLOB_RECURSE onnxruntime_providers_webgpu_cc_srcs CONFIGURE_DEPENDS
    "${ONNXRUNTIME_ROOT}/core/providers/webgpu/*.h"
    "${ONNXRUNTIME_ROOT}/core/providers/webgpu/*.cc"
  )
  if(onnxruntime_USE_EXTERNAL_DAWN OR CMAKE_SYSTEM_NAME STREQUAL "Emscripten")
    list(REMOVE_ITEM onnxruntime_providers_webgpu_cc_srcs
      "${ONNXRUNTIME_ROOT}/core/providers/webgpu/webgpu_context_dawn_platform.cc")
  endif()
  if(NOT onnxruntime_DISABLE_CONTRIB_OPS)
    list(APPEND onnxruntime_providers_webgpu_cc_srcs ${onnxruntime_webgpu_contrib_ops_cc_srcs})
  endif()

  if(NOT onnxruntime_USE_EP_API_ADAPTERS)
    #
    # Build WebGPU EP as an internal (non-plugin) static library
    #

    # For static library build, exclude the 'ep' folder
    file(GLOB_RECURSE ep_files_to_exclude
      "${ONNXRUNTIME_ROOT}/core/providers/webgpu/ep/*.h"
      "${ONNXRUNTIME_ROOT}/core/providers/webgpu/ep/*.cc"
    )
    list(REMOVE_ITEM onnxruntime_providers_webgpu_cc_srcs ${ep_files_to_exclude})

    source_group(TREE ${ONNXRUNTIME_ROOT} FILES ${onnxruntime_providers_webgpu_cc_srcs})
    onnxruntime_add_static_library(onnxruntime_providers_webgpu ${onnxruntime_providers_webgpu_cc_srcs})
    onnxruntime_add_include_to_target(onnxruntime_providers_webgpu
      onnxruntime_common onnx onnx_proto flatbuffers::flatbuffers Boost::mp11 safeint_interface)
  elseif(onnxruntime_WEBGPU_STATIC_PLUGIN)
    #
    # Build WebGPU EP as a plugin EP that is statically linked into the ORT binary.
    #
    # This uses the same plugin EP sources ('ep' folder) and EP API adapters as the shared library build below.
    # The difference is only in how the EP reaches the application: ORT core registers it at OrtEnv creation time
    # instead of the application calling RegisterExecutionProviderLibrary() with a library path.
    #
    source_group(TREE ${ONNXRUNTIME_ROOT} FILES ${onnxruntime_providers_webgpu_cc_srcs})
    onnxruntime_add_static_library(onnxruntime_providers_webgpu ${onnxruntime_providers_webgpu_cc_srcs})
    onnxruntime_add_include_to_target(onnxruntime_providers_webgpu
      onnxruntime_common onnx onnx_proto flatbuffers::flatbuffers Boost::mp11 safeint_interface)

    # ORT_PLUGIN_EP_SKIP_API_MANUAL_INIT tells the shared plugin EP headers that OrtGetApiBase() is available
    # in-process, so the C++ API must not be built with ORT_API_MANUAL_INIT (the rest of the binary is not).
    target_compile_definitions(onnxruntime_providers_webgpu PRIVATE
                               ORT_PLUGIN_EP_STATICALLY_LINKED=1
                               ORT_PLUGIN_EP_SKIP_API_MANUAL_INIT=1)
  else()
    #
    # Build WebGPU EP as a shared library
    #
    if(WIN32)
      # Sets the DLL version info on Windows: https://learn.microsoft.com/en-us/windows/win32/menurc/versioninfo-resource
      list(APPEND onnxruntime_providers_webgpu_cc_srcs "${ONNXRUNTIME_ROOT}/core/providers/webgpu/ep/versioninfo.rc")
    endif()
    source_group(TREE ${ONNXRUNTIME_ROOT} FILES ${onnxruntime_providers_webgpu_cc_srcs})

    onnxruntime_add_shared_library_module(onnxruntime_providers_webgpu ${onnxruntime_providers_webgpu_cc_srcs})
    onnxruntime_add_include_to_target(onnxruntime_providers_webgpu
        ${REPO_ROOT}/include/onnxruntime/core/session
        onnxruntime_common
        onnx
        onnx_proto
        flatbuffers::flatbuffers
        Boost::mp11
        safeint_interface)

    target_link_libraries(onnxruntime_providers_webgpu PRIVATE
        onnxruntime_optimizer
        ${onnxruntime_providers_target}
        onnxruntime_lora
        onnxruntime_framework
        onnxruntime_graph
        onnxruntime_util
        ${ONNXRUNTIME_MLAS_LIBS}
        onnxruntime_common
        onnxruntime_flatbuffers
        ${onnxruntime_EXTERNAL_LIBRARIES}
    )

    # Add ONNX compiler definitions
    add_definitions("-DONNX_ML=1")
    add_definitions("-DONNX_NAMESPACE=onnx")
    add_definitions("-DONNX_USE_LITE_PROTO=1")

    # Set preprocessor definitions used in onnxruntime_providers_webgpu.rc
    if(WIN32)
      set(WEBGPU_DLL_FILE_DESCRIPTION "ONNX Runtime WebGPU Provider")

      target_compile_definitions(onnxruntime_providers_webgpu PRIVATE FILE_DESC=\"${WEBGPU_DLL_FILE_DESCRIPTION}\")
      target_compile_definitions(onnxruntime_providers_webgpu PRIVATE FILE_NAME=\"onnxruntime_providers_webgpu.dll\")
    endif()

    # Set linker flags for function(s) exported by EP DLL
    if(UNIX)
      if (APPLE)
        set_property(TARGET onnxruntime_providers_webgpu APPEND_STRING PROPERTY LINK_FLAGS
                     "-Xlinker -dead_strip")
      elseif (NOT CMAKE_SYSTEM_NAME MATCHES "AIX")
        target_link_options(onnxruntime_providers_webgpu PRIVATE
                            "LINKER:--version-script=${ONNXRUNTIME_ROOT}/core/providers/webgpu/ep/version_script.lds"
                            "LINKER:--gc-sections"
                            "LINKER:-rpath=\$ORIGIN")
        # TODO: -z noexecstack
      endif()
    elseif(WIN32)
      set_property(TARGET onnxruntime_providers_webgpu APPEND_STRING PROPERTY LINK_FLAGS
                   "-DEF:${ONNXRUNTIME_ROOT}/core/providers/webgpu/ep/symbols.def")
    else()
      message(FATAL_ERROR "onnxruntime_providers_webgpu unknown platform, need to specify shared library exports for it")
    endif()

    set_target_properties(onnxruntime_providers_webgpu PROPERTIES LINKER_LANGUAGE CXX)

    if (onnxruntime_BUILD_CACHE)
      message(FATAL_ERROR "WebGPU EP shared library build does not support build cache. Please disable build cache or use static library build.")
    endif()
    if (CMAKE_SYSTEM_NAME STREQUAL "Emscripten")
      message(FATAL_ERROR "WebGPU EP shared library build is not supported on Emscripten. Please use '--use_webgpu static_plugin'.")
    endif()
  endif()

  if (onnxruntime_USE_EP_API_ADAPTERS)
    #
    # Settings common to both plugin EP builds (shared library and statically linked).
    #

    # Default plugin EP version to ORT_VERSION with "-dev" suffix if not explicitly provided.
    if(NOT DEFINED onnxruntime_PLUGIN_EP_VERSION)
      set(onnxruntime_PLUGIN_EP_VERSION "${ORT_VERSION}-dev")
    endif()

    # Set preprocessor definition for plugin EP version
    target_compile_definitions(onnxruntime_providers_webgpu PRIVATE
                               ORT_PLUGIN_EP_VERSION="${onnxruntime_PLUGIN_EP_VERSION}")

    # Bake the minimum compatible ORT version (the single source of truth lives in
    # plugin-ep-webgpu/MIN_ONNXRUNTIME_VERSION) into the EP so it can be enforced at runtime.
    # Format is strict "MAJOR.MINOR.PATCH".
    set(_ORT_PLUGIN_EP_WEBGPU_MIN_ORT_VERSION_FILE "${REPO_ROOT}/plugin-ep-webgpu/MIN_ONNXRUNTIME_VERSION")
    file(STRINGS "${_ORT_PLUGIN_EP_WEBGPU_MIN_ORT_VERSION_FILE}" _ORT_PLUGIN_EP_WEBGPU_MIN_ORT_VERSION LIMIT_COUNT 1)
    if(NOT _ORT_PLUGIN_EP_WEBGPU_MIN_ORT_VERSION)
      message(FATAL_ERROR "WebGPU plugin EP minimum ORT version file is missing or empty: "
                          "${_ORT_PLUGIN_EP_WEBGPU_MIN_ORT_VERSION_FILE}")
    endif()
    target_compile_definitions(onnxruntime_providers_webgpu PRIVATE
                               ORT_PLUGIN_EP_MIN_ORT_VERSION="${_ORT_PLUGIN_EP_WEBGPU_MIN_ORT_VERSION}")

    # Configure precompiled headers for the plugin EP build.
    # PCH ensures ep/adapters.h is included first and improves compilation speed.
    target_precompile_headers(onnxruntime_providers_webgpu PRIVATE
      "${REPO_ROOT}/include/onnxruntime/ep/adapters.h"
    )

    # Suppress -Werror=maybe-uninitialized. The EP adapter types are defined entirely inline in headers,
    # so GCC sees through the failure and exception paths of accessors like OpKernelInfo::GetAttr<> and
    # falsely warns about values that are only read once the call has succeeded. It also produces false
    # positives deep inside absl::InlinedVector for locals that are always constructed.
    # This mirrors the same suppression on the CUDA plugin EP target.
    target_compile_options(onnxruntime_providers_webgpu PRIVATE
      $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CXX_COMPILER_ID:GNU>>:-Wno-maybe-uninitialized>
    )
  endif()

  set_target_properties(onnxruntime_providers_webgpu PROPERTIES CXX_STANDARD_REQUIRED ON)
  set_target_properties(onnxruntime_providers_webgpu PROPERTIES FOLDER "ONNXRuntime")

  if (CMAKE_SYSTEM_NAME STREQUAL "Emscripten")
    # target "emdawnwebgpu_c" is created by Dawn, including "-fno-exceptions" in its compile options by default.
    #
    # in ONNX Runtime build, "-s DISABLE_EXCEPTION_CATCHING=0" is appended to CMAKE_CXX_FLAGS by default unless build flag
    # "--disable_wasm_exception_catching" is specified. It is not compatible with "-fno-exceptions".
    #
    # if "-s DISABLE_EXCEPTION_CATCHING=0" is set, we need to remove "-fno-exceptions" from emdawnwebgpu_c
    if (CMAKE_CXX_FLAGS MATCHES "DISABLE_EXCEPTION_CATCHING=0")
      get_property(EM_DAWN_WEBGPU_C_COMPILE_OPTIONS TARGET emdawnwebgpu_c PROPERTY COMPILE_OPTIONS)
      list(REMOVE_ITEM EM_DAWN_WEBGPU_C_COMPILE_OPTIONS "-fno-exceptions")
      set_property(TARGET emdawnwebgpu_c PROPERTY COMPILE_OPTIONS ${EM_DAWN_WEBGPU_C_COMPILE_OPTIONS})
    endif()
    if (CMAKE_CXX_FLAGS MATCHES "-fwasm-exceptions")
      get_property(EM_DAWN_WEBGPU_C_COMPILE_OPTIONS TARGET emdawnwebgpu_c PROPERTY COMPILE_OPTIONS)
      list(REMOVE_ITEM EM_DAWN_WEBGPU_C_COMPILE_OPTIONS "-fno-exceptions")
      set_property(TARGET emdawnwebgpu_c PROPERTY COMPILE_OPTIONS ${EM_DAWN_WEBGPU_C_COMPILE_OPTIONS})
    endif()

    # target "emdawnwebgpu_cpp" is created by Dawn. When it is linked to onnxruntime_providers_webgpu as "PUBLIC"
    # dependency, a few build/link flags will be set automatically to make sure emscripten can generate correct
    # WebAssembly/JavaScript code for WebGPU support.
    target_link_libraries(onnxruntime_providers_webgpu PUBLIC emdawnwebgpu_cpp)

    # We need to manually add the Dawn include directories so that generated Emscripten WebGPU
    # headers (e.g. webgpu_enum_class_bitmasks.h) are found at compile time.
    #
    # IMPORTANT: We must add the generated emdawnwebgpu include directory BEFORE the Dawn source
    # include directory, because ${dawn_SOURCE_DIR}/include/webgpu/webgpu_cpp.h is a stub that
    # redirects to dawn/webgpu_cpp.h (native Dawn), but we need the generated Emscripten-specific
    # webgpu_cpp.h.
    target_include_directories(onnxruntime_providers_webgpu PRIVATE
        "${dawn_BINARY_DIR}/gen/src/emdawnwebgpu/include"
        "${dawn_SOURCE_DIR}/include"
    )

    if (onnxruntime_ENABLE_WEBASSEMBLY_JSPI)
      target_link_options(onnxruntime_providers_webgpu PUBLIC
        "SHELL:-s JSPI=1"
      )
    else()
      # ASYNCIFY is required for WGPUFuture support (ie. async functions in WebGPU API)
      target_link_options(onnxruntime_providers_webgpu PUBLIC
        "SHELL:-s ASYNCIFY=1"
        "SHELL:-s ASYNCIFY_STACK_SIZE=65536"
      )
    endif()
  else()
    onnxruntime_add_include_to_target(onnxruntime_providers_webgpu dawn::dawncpp_headers dawn::dawn_headers)

    set(onnxruntime_providers_webgpu_dll_deps)

    # Delay-load user32.dll which is pulled in by the WebGPU EP build.
    # This allows onnxruntime.dll to load in processes with
    # MITIGATION_WIN32K_DISABLE (e.g., a sandboxed process under Win32k lockdown).
    # ORT's device discovery already skips SetupDi calls when Win32k syscalls
    # are disallowed (Win32kSystemCallsDisallowed() in device_discovery.cc),
    # so user32.dll is never actually needed in those processes.
    if (WIN32 AND onnxruntime_ENABLE_DELAY_LOADING_WIN_DLLS)
      list(APPEND onnxruntime_DELAYLOAD_FLAGS "/DELAYLOAD:user32.dll")
    endif()

    if (NOT onnxruntime_USE_EXTERNAL_DAWN)
      # The WebGPU EP configures the bundled Dawn instance with a custom dawn::platform::Platform,
      # so it must link dawn_platform to resolve the platform base-class typeinfo/vtable symbols.
      target_link_libraries(onnxruntime_providers_webgpu PRIVATE dawn::dawn_platform)
    endif()

    if (onnxruntime_BUILD_DAWN_SHARED_LIBRARY)
      target_link_libraries(onnxruntime_providers_webgpu PUBLIC dawn::webgpu_dawn)

      if (WIN32)
        if (onnxruntime_ENABLE_DELAY_LOADING_WIN_DLLS)
          list(APPEND onnxruntime_DELAYLOAD_FLAGS "/DELAYLOAD:webgpu_dawn.dll")
        endif()

        # TODO: the following code is used to disable building Dawn using vcpkg temporarily
        # until we figure out how to resolve the packaging pipeline failures
        #
        # if (onnxruntime_USE_VCPKG)
        if (FALSE)
          # Fix Dawn vcpkg build issue (missing IMPORTED_IMPLIB and IMPORTED_LOCATION for target dawn::webgpu_dawn)
          get_target_property(webgpu_dawn_target_IMPORTED_IMPLIB dawn::webgpu_dawn IMPORTED_IMPLIB)
          if (NOT webgpu_dawn_target_IMPORTED_IMPLIB)
            set_target_properties(dawn::webgpu_dawn PROPERTIES IMPORTED_IMPLIB "webgpu_dawn.lib")
          endif()
          get_target_property(webgpu_dawn_target_IMPORTED_LOCATION dawn::webgpu_dawn IMPORTED_LOCATION)
          if (NOT webgpu_dawn_target_IMPORTED_LOCATION)
            set_target_properties(dawn::webgpu_dawn PROPERTIES IMPORTED_LOCATION "webgpu_dawn.dll")
          endif()
        endif()
      endif()

      list(APPEND onnxruntime_providers_webgpu_dll_deps "$<TARGET_FILE:dawn::webgpu_dawn>")
    else()
      if (NOT onnxruntime_USE_EXTERNAL_DAWN)
        target_link_libraries(onnxruntime_providers_webgpu PRIVATE dawn::dawn_native)
      endif()
      target_link_libraries(onnxruntime_providers_webgpu PRIVATE dawn::dawn_proc)
    endif()

    if (WIN32 AND onnxruntime_ENABLE_DAWN_BACKEND_D3D12 AND NOT onnxruntime_DAWN_PREBUILT_DIR)
      # Ensure dxcompiler.dll exists in the output directory $<TARGET_FILE_DIR:dxcompiler>
      # TODO: the following code is used to disable building Dawn using vcpkg temporarily
      # until we figure out how to resolve the packaging pipeline failures
      #
      # if (onnxruntime_USE_VCPKG)
      if (FALSE)
        find_package(directx-dxc CONFIG REQUIRED)
        target_link_libraries(onnxruntime_providers_webgpu Microsoft::DirectXShaderCompiler)
        list(APPEND onnxruntime_providers_webgpu_dll_deps "$<TARGET_FILE:Microsoft::DirectXShaderCompiler>")
      else()
        add_dependencies(onnxruntime_providers_webgpu dxcompiler)

        list(APPEND onnxruntime_providers_webgpu_dll_deps "$<TARGET_FILE_DIR:dxcompiler>/dxcompiler.dll")
      endif()
    endif()

    # In the plugin EP shared library build the WebGPU EP is its own DLL
    # (onnxruntime_providers_webgpu.dll) rather than being linked into onnxruntime.dll, so the
    # delay-load flags accumulated above (notably /DELAYLOAD:user32.dll) must be applied to THIS target.
    # Without it the DLL keeps a static import on user32.dll and fails to load in a Win32k-lockdown sandbox
    # (e.g. Chromium's WebNN compiler process): 'depends on "USER32.dll" which is missing' (Error 1359).
    # When the EP is linked into the ORT binary these same flags are applied to the onnxruntime target in
    # onnxruntime.cmake.
    if (WIN32 AND NOT onnxruntime_WEBGPU_LINKED_INTO_HOST AND onnxruntime_DELAYLOAD_FLAGS)
      target_link_options(onnxruntime_providers_webgpu PRIVATE ${onnxruntime_DELAYLOAD_FLAGS})
      target_link_libraries(onnxruntime_providers_webgpu PRIVATE delayimp.lib)
    endif()

    if (onnxruntime_providers_webgpu_dll_deps)
      # Copy dependency DLLs to the output directory
      add_custom_command(
        TARGET onnxruntime_providers_webgpu
        POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_if_different "${onnxruntime_providers_webgpu_dll_deps}" "$<TARGET_FILE_DIR:onnxruntime_providers_webgpu>"
        COMMAND_EXPAND_LISTS
        VERBATIM )
    endif()
  endif()

  add_dependencies(onnxruntime_providers_webgpu onnx ${onnxruntime_EXTERNAL_DEPENDENCIES})

  if (onnxruntime_USE_WEBGPU)
    # The Python wgsl-gen tool lives at the repo level under tools/python.
    set(WGSL_GEN_PYTHON_DIR "${REPO_ROOT}/tools/python")
    set(WGSL_GENERATED_ROOT "${CMAKE_CURRENT_BINARY_DIR}/wgsl_generated")

    # The top-level find_package(Python ...) in cmake/CMakeLists.txt is gated
    # on BUILD_SHARED_LIB OR ENABLE_PYTHON, so Python_EXECUTABLE is not always
    # set in WebGPU-enabled builds (e.g. the WASM lane). Find Python ourselves
    # so this branch works in every config.
    find_package(Python 3.10 COMPONENTS Interpreter REQUIRED)

    set(WGSL_GENERATED_DIR "${WGSL_GENERATED_ROOT}/wgsl_template_gen")
    # Define the output files that will be generated
    set(WGSL_GENERATED_INDEX_H "${WGSL_GENERATED_DIR}/index.h")
    set(WGSL_GENERATED_INDEX_IMPL_H "${WGSL_GENERATED_DIR}/index_impl.h")

    # Ensure the output directory exists
    file(MAKE_DIRECTORY ${WGSL_GENERATED_DIR})

    # Find all WGSL template input files
    set(WGSL_SEARCH_PATHS "${ONNXRUNTIME_ROOT}/core/providers/webgpu/*.wgsl.template")
    if(NOT onnxruntime_DISABLE_CONTRIB_OPS)
        list(APPEND WGSL_SEARCH_PATHS "${ONNXRUNTIME_ROOT}/contrib_ops/webgpu/*.wgsl.template")
    endif()
    file(GLOB_RECURSE WGSL_TEMPLATE_FILES ${WGSL_SEARCH_PATHS})

    # Set wgsl-gen command line options as a list
    set(WGSL_GEN_OPTIONS
        "--output" "${WGSL_GENERATED_DIR}"
        "-I" "wgsl_template_gen/"
        "--preserve-code-ref"
        "--verbose"
        "-i" "${ONNXRUNTIME_ROOT}/core/providers/webgpu"
    )
    if(NOT onnxruntime_DISABLE_CONTRIB_OPS)
        list(APPEND WGSL_GEN_OPTIONS "-i" "${ONNXRUNTIME_ROOT}/contrib_ops/webgpu")
    endif()

    if (CMAKE_BUILD_TYPE STREQUAL "Debug")
      list(APPEND WGSL_GEN_OPTIONS "--generator" "static-cpp-literal")
    else()
      list(APPEND WGSL_GEN_OPTIONS "--generator" "static-cpp")
    endif()

    # Generate WGSL templates
    add_custom_command(
      OUTPUT ${WGSL_GENERATED_INDEX_H} ${WGSL_GENERATED_INDEX_IMPL_H}
      COMMAND ${Python_EXECUTABLE} "${WGSL_GEN_PYTHON_DIR}/wgsl_gen.py" ${WGSL_GEN_OPTIONS}
      DEPENDS ${WGSL_TEMPLATE_FILES}
      WORKING_DIRECTORY ${WGSL_GEN_PYTHON_DIR}
      COMMENT "Generating WGSL templates from *.wgsl.template files (Python)"
      COMMAND_EXPAND_LISTS
      VERBATIM
    )

    add_custom_target(onnxruntime_webgpu_wgsl_generation
      DEPENDS ${WGSL_GENERATED_INDEX_H} ${WGSL_GENERATED_INDEX_IMPL_H}
      SOURCES ${WGSL_TEMPLATE_FILES}
    )

    # Add the generated directory to include paths
    target_include_directories(onnxruntime_providers_webgpu PRIVATE ${WGSL_GENERATED_ROOT})

    # Make sure generation happens before building the provider
    add_dependencies(onnxruntime_providers_webgpu onnxruntime_webgpu_wgsl_generation)
  endif()

  if (NOT onnxruntime_BUILD_SHARED_LIB)
    install(TARGETS onnxruntime_providers_webgpu EXPORT ${PROJECT_NAME}Targets
            ARCHIVE   DESTINATION ${CMAKE_INSTALL_LIBDIR}
            LIBRARY   DESTINATION ${CMAKE_INSTALL_LIBDIR}
            RUNTIME   DESTINATION ${CMAKE_INSTALL_BINDIR}
            FRAMEWORK DESTINATION ${CMAKE_INSTALL_BINDIR})
  endif()
