# 测试源码含 UTF-8 中文诊断/断言消息；MSVC 默认代码页 936 会把多字节
# 序列误解析为换行/引号，统一按 UTF-8 编译（仅 tests 目录作用域）。
if(MSVC)
    add_compile_options(/utf-8)
endif()

function(add_vde_test name)
    # 默认源文件为 ${name}.cpp；可通过 SRCS 参数显式指定（用于 target 名与文件名不一致的场景）
    set(_srcs ${name}.cpp)
    set(_args ${ARGN})
    list(FIND _args "SRCS" _src_pos)
    if(_src_pos GREATER -1)
        math(EXPR _src_idx "${_src_pos} + 1")
        list(GET _args ${_src_idx} _srcs)
    endif()
    add_executable(${name} ${_srcs})
    target_link_libraries(${name} PRIVATE vde GTest::gtest GTest::gtest_main)
    target_include_directories(${name} PRIVATE
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../../include>
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/..>
    )
    target_compile_definitions(${name} PRIVATE VDE_TEST_TEMP_DIR="${VDE_TEST_TEMP_DIR}")
    # C API 测试在 Windows 需要 vde_capi.dll 同目录；gtest_discover_tests
    # 会在构建期运行 exe，因此复制必须发生在 discover 之前（COPY_CAPI）。
    list(FIND _args "COPY_CAPI" _copy_capi_pos)
    if(_copy_capi_pos GREATER -1)
        set(_capi_dll_target "")
        if(TARGET vde_capi_shared)
            set(_capi_dll_target vde_capi_shared)
        elseif(TARGET vde_capi)
            set(_capi_dll_target vde_capi)
        endif()
        if(_capi_dll_target)
            add_dependencies(${name} ${_capi_dll_target})
            add_custom_command(TARGET ${name} POST_BUILD
                COMMAND ${CMAKE_COMMAND} -E copy_if_different
                    "$<TARGET_FILE:${_capi_dll_target}>"
                    "$<TARGET_FILE_DIR:${name}>")
        endif()
    endif()
    # 每测试超时（秒）：防止环境级挂起（如单线程 UserRequest 等待）拖死整轮 CI；
    # 正常运行远低于该值（最长合法用例 FuzzBoolean.RandomSelfOperations ~255s）。
    # P4-64：按已知慢/易超时用例分档，并统一加 labels（unit;debug / fuzz / perf / slow）。
    # gtest_discover_tests 的 PROPERTIES 值按单值传递；每类只设一个主标签：
    # debug（普通）/ fuzz / perf / slow（regression + 已知慢）。
    set(_vde_test_label "debug")
    set(_vde_test_timeout 600)
    if(CMAKE_BUILD_TYPE STREQUAL "Debug")
        set(_vde_test_timeout 900)
    endif()
    if(name MATCHES "fuzz")
        set(_vde_test_label "fuzz")
        set(_vde_test_timeout 900)
        if(CMAKE_BUILD_TYPE STREQUAL "Debug")
            set(_vde_test_timeout 1500)
        endif()
    elseif(name MATCHES "benchmark|perf")
        set(_vde_test_label "perf")
        set(_vde_test_timeout 600)
        if(CMAKE_BUILD_TYPE STREQUAL "Debug")
            set(_vde_test_timeout 900)
        endif()
    elseif(name MATCHES "regression")
        set(_vde_test_label "slow")
        set(_vde_test_timeout 600)
        if(CMAKE_BUILD_TYPE STREQUAL "Debug")
            set(_vde_test_timeout 900)
        endif()
    endif()
    # 目标级测试隔离（只加 ctest 运行属性，不改任何断言/验收强度）：
    # - test_boolean_benchmark：box−sphere 基准自身含 `EXPECT_LT(ms, 2000)` 墙钟断言
    #   （历史整例均值 2.17s、实测负载下 wall_ms 抖动 428–1527ms，裕度仅 ~25%），
    #   并发负载会把它拖过 2s 而 flaky；该 exe 仅 1 个用例，整目标 RUN_SERIAL
    #   使其独占运行（ctest 不与其他用例并发）。详见 docs/reference/486。
    # 注：test_ssi_boolean 的 OMP_NUM_THREADS=1 过渡隔离已在 src/brep 竞态修复
    # （commit 84fd9c0d）后移除；默认 OpenMP 下复测须保持稳定。
    # test_curved_boolean_baseline 记录 legacy 失败形态（含体积边界布尔），
    # 极端并发负载下 legacy 布尔偶发非确定性会影响该"记录型"断言；
    # 串行化保证 CB0 基线数字可复现（根因改进见 docs/reference/486）。
    # test_topology_naming_facade：W10/W16 的 TNP 命名记录开销用「绝对 200us + 相对布尔
    # 耗时 10%」双口径，-j8 并发下布尔耗时被争抢放大而记录层（纯 CPU 短脉冲）抖动小，
    # 相对比在 1.0.486 预 bump 全量中升到 11.68% 而后台占用消失后单跑 4.89%——属负载口径
    # 失真，故整目标 RUN_SERIAL（只改 ctest 运行属性，断言强度与阈值不变）。
    # test_boolean_oracle_metrics：W22 表示无关矩阵用例含 experimental CBRA 探查
    # （w22_cbra_reexpress，6s hard wall-clock budget）。1.0.489 预 bump -j8 全量中
    # f09 的 CBRA 探查因相邻用例争抢 CPU 超时→expressible=1，而隔离运行稳定=2
    # （7/7 PASS、矩阵 45 格）；属负载口径失真而非几何/断言问题，故整目标 RUN_SERIAL
    # （只改 ctest 运行属性，断言强度与阈值不变）。
    # test_curved_boolean_topology：W99/W101 的 UV 加速双口径性能断言用
    # 「同进程交替 3 次中位比 + 10% 相对 + 5ms 粒度」；1.0.491 预 bump -j8 全量中
    # 出现 off_ms=333/on_ms=379 > 371.3ms（相邻 heavy 用例争抢 CPU），隔离单跑可过；
    # 属负载口径失真而非几何/断言问题，故整目标 RUN_SERIAL（只改 ctest 运行属性，
    # 断言强度与阈值不变）。
    # test_vde_format：VdeV2Forward.* 会故意破坏头/段版本后再 deserialize；解析器在
    # 报错前可能按损坏长度尝试一次分配，1.0.493 预 bump -j8 全量中内存压力下该分配
    # 先抛出 std::bad_alloc（期望 std::runtime_error），隔离单跑 20/20 稳定通过；
    # 属负载下分配失败口径，非解析语义变化，故整目标 RUN_SERIAL（断言强度不变）。
    # test_industrial_formats：Wave4Interop.XT 判定走格式探测/能力矩阵，1.0.493 预 bump
    # -j8 全量中与相邻重型用例并发时探测降级为 malformed（期望 unsupported），隔离
    # 单跑稳定通过；属并发探测口径失真，故整目标 RUN_SERIAL（断言强度不变）。
    if(name STREQUAL "test_boolean_benchmark" OR
       name STREQUAL "test_curved_boolean_baseline" OR
       name STREQUAL "test_curved_boolean_topology" OR
       name STREQUAL "test_measure_planar_spanned" OR
       name STREQUAL "test_topology_naming_facade" OR
       name STREQUAL "test_boolean_oracle_metrics" OR
       name STREQUAL "test_vde_format" OR
       name STREQUAL "test_industrial_formats")
        set(_vde_test_run_serial TRUE)
    endif()
    set(_vde_discover_props PROPERTIES TIMEOUT ${_vde_test_timeout}
        LABELS "${_vde_test_label}")
    if(_vde_test_run_serial)
        list(APPEND _vde_discover_props RUN_SERIAL TRUE)
    endif()
    gtest_discover_tests(${name} ${_vde_discover_props})
endfunction()

# 测试数据目录约定（task-59 C-2 方案 B：合成夹具入库，普通 ctest 开箱即验证）
# 默认读取入库夹具 tests/data/fixtures/（小体积、确定性、可再生成，约 415KB），
# 使 22 项原先因缺语料/夹具而 Skipped 的用例在默认 ctest 中直接运行。
# 真实语料/用户模型可用 CMake 缓存变量覆盖（configure 时 -D...）：
#   -DVDE_REAL_CORPUS_DIR=<repo>/corpus/real
#   -DVDE_REALFILE_DIR=<repo>/corpus/realfile
#   -DVDE_FIXTURE_ROOT=<自定义夹具根>
set(VDE_FIXTURE_ROOT "${CMAKE_SOURCE_DIR}/tests/data/fixtures" CACHE PATH
    "Synthetic in-repo fixture root (committed, generated by tools/test_fixtures)")
set(VDE_REAL_CORPUS_DIR "${VDE_FIXTURE_ROOT}/real" CACHE PATH
    "Real model corpus dir (synthetic DWG fixtures by default; override to <repo>/corpus/real)")
# 原生 CAD 回归默认使用工程目录下的 corpus/real（存在时），
# 避免每个开发者都要手动 -D；语料缺失时回退到 fixtures。
set(VDE_NATIVE_CORPUS_DIR "${CMAKE_SOURCE_DIR}/corpus/real" CACHE PATH
    "Real corpus for native CAD regression (SLDPRT/CATPart/STEP)")
set(VDE_REALFILE_DIR "${CMAKE_SOURCE_DIR}/corpus/realfile" CACHE PATH
    "User real-model drop-in dir (not in git)")

# 测试目录按对应模块的启用状态门控（VDE-013）：模块被关闭时不构建其测试，
# 避免链接到未构建的 target。fuzz/regression/benchmark 依赖几何内核，随 brep 门控。
if(VDE_ENABLE_capi)
add_subdirectory(capi)
endif()
# 微内核 P0：插件管理器/示例插件端到端测试（VDE_BUILD_PLUGIN=OFF 时不构建，
# 避免链接到未构建的 vde_plugin）
if(VDE_ENABLE_plugin)
add_subdirectory(plugin)
endif()
if(VDE_ENABLE_core)
add_subdirectory(core)
endif()
if(VDE_ENABLE_curves)
add_subdirectory(curves)
endif()
if(VDE_ENABLE_mesh)
add_subdirectory(mesh)
endif()
# P2-1：CAE/CFD 前处理模块测试（从 tests/mesh 迁出）
if(VDE_ENABLE_cae)
add_subdirectory(cae)
endif()
if(VDE_ENABLE_spatial)
add_subdirectory(spatial)
endif()
if(VDE_ENABLE_collision)
add_subdirectory(collision)
endif()
if(VDE_ENABLE_compute)
add_subdirectory(compute)  # E3c: compute backend — GPU/CPU 计算后端抽象
endif()
if(VDE_ENABLE_boolean)
add_subdirectory(boolean)
endif()
if(VDE_ENABLE_brep)
add_subdirectory(brep)
endif()
if(VDE_ENABLE_sdf)
add_subdirectory(sdf)
endif()
if(VDE_ENABLE_sketch)
add_subdirectory(sketch)
endif()
if(VDE_ENABLE_foundation)
add_subdirectory(foundation)
endif()
if(VDE_ENABLE_brep)
add_subdirectory(fuzz)
add_subdirectory(regression)
add_subdirectory(benchmark)
endif()
if(VDE_ENABLE_render)
add_subdirectory(render)
endif()
# 拆分出的独立模块测试
if(VDE_ENABLE_expression)
add_subdirectory(expression)
endif()
if(VDE_ENABLE_param)
add_subdirectory(param)   # E4c: 参数化表达式引擎（vde::param）
endif()
if(VDE_ENABLE_infra)
add_subdirectory(infra)
endif()
if(VDE_ENABLE_mechanism)
add_subdirectory(mechanism)
endif()
if(VDE_ENABLE_pdm)
add_subdirectory(pdm)
endif()
if(VDE_ENABLE_license)
add_subdirectory(license)
endif()
if(VDE_ENABLE_ui)
add_subdirectory(ui)
endif()
if(VDE_ENABLE_cam)
add_subdirectory(cam)
endif()
if(VDE_ENABLE_drafting)
add_subdirectory(drafting)
endif()
# WP-P4-09 Plan A：PMI 导出/自动生成操作模块（vde_pmi；PMI 关闭时不构建）
if(VDE_ENABLE_pmi)
add_subdirectory(vde_pmi)
endif()

# P4-64：手动注册的慢/工具类测试设置 TIMEOUT 与 labels（gtest_discover_tests 之外）。
# 已知慢来源：插件 tool scaffold/index/remote/package/upgrade、Python ctypes smoke、
# ABI 矩阵、索引安装；Debug 下放宽，避免 CI 环境抖动误杀。
foreach(_vde_manual_test
        VDE_PluginToolScaffoldSmoke
        VDE_PluginToolLintSmoke
        VDE_PluginToolIndexRevocation
        VDE_PluginToolMesherAbi
        VDE_PluginToolPackageListUninstall
        VDE_PluginToolUpgrade
        VDE_PluginToolRemoteInstallTest
        VDE_PythonCtypesSmoke)
    if(TEST ${_vde_manual_test})
        set_tests_properties(${_vde_manual_test} PROPERTIES
            LABELS "tool;slow"
            TIMEOUT 900)
    endif()
endforeach()

# 显式慢标签汇总（可用 ctest -L slow / -L fuzz / -L perf 分批跑）。
# Debug 档见 add_vde_test 的 TIMEOUT 分档；Release 档默认 600s（fuzz 900s）。
# P1-1/P2-2/P2-3: corpus gate (empty-corpus fake-green guard) + fixed sample manifest.
# Synthetic self-test uses temp dirs for empty/non-empty/garbage/manifest/exit-code
# coverage and never depends on real corpus.
# Config gate is registered only when configured dirs actually contain files.
# 选择可用的 Python 解释器：优先 find_package(Python3)，回退 PATH 上的
# python3/python；解释器必须实际可执行。Windows 上 py/pymanager stub 可能
# 在 PATH 上但没有任何 runtime，直接注册成 CTest 会全部失败。
if(NOT DEFINED VDE_CORPUS_GATE_PYTHON)
    if(Python3_Interpreter_FOUND)
        set(VDE_CORPUS_GATE_PYTHON "${Python3_EXECUTABLE}")
    else()
        find_program(VDE_CORPUS_GATE_PYTHON NAMES python3 python)
    endif()
endif()
if(VDE_CORPUS_GATE_PYTHON)
    execute_process(
        COMMAND "${VDE_CORPUS_GATE_PYTHON}" -c
            "import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)"
        RESULT_VARIABLE _vde_py_ok
        OUTPUT_QUIET ERROR_QUIET)
    if(NOT _vde_py_ok EQUAL 0)
        message(STATUS
            "VDE corpus gate: '${VDE_CORPUS_GATE_PYTHON}' is not a working Python >= 3.8; "
            "python-based tests skipped (reconfigure with -DVDE_CORPUS_GATE_PYTHON=<python.exe>)")
        unset(VDE_CORPUS_GATE_PYTHON)
        unset(VDE_CORPUS_GATE_PYTHON CACHE)
    endif()
endif()

# 平台 CI 配置静态自检：CMakePresets / tools/ci 脚本 / workflow 模板。
if(TARGET vde_gpu_probe)
    add_test(NAME VDE_GpuProbeSelfTest
        COMMAND vde_gpu_probe --points 1024 --json)
    set_tests_properties(VDE_GpuProbeSelfTest PROPERTIES
        LABELS "gpu;debug" TIMEOUT 120)
endif()

if(VDE_CORPUS_GATE_PYTHON)
    add_test(NAME VDE_CIPlatformValidation
        COMMAND "${VDE_CORPUS_GATE_PYTHON}"
            "${CMAKE_SOURCE_DIR}/tools/ci/validate_ci.py"
            --root "${CMAKE_SOURCE_DIR}")
    set_tests_properties(VDE_CIPlatformValidation PROPERTIES
        LABELS "ci;debug" TIMEOUT 60)
endif()

# 源码审计：禁止 thread_local 非平凡析构对象（MinGW GCC 16.1 UCRT
# TLS 析构缺陷，见 docs/reference/132；独立脚本可手工运行）。
if(VDE_CORPUS_GATE_PYTHON)
    add_test(NAME VDE_ThreadLocalAudit
        COMMAND "${VDE_CORPUS_GATE_PYTHON}"
            "${CMAKE_SOURCE_DIR}/tools/kernel_audit/thread_local_audit.py"
            --root "${CMAKE_SOURCE_DIR}" --self-test)
    set_tests_properties(VDE_ThreadLocalAudit PROPERTIES
        LABELS "tool;debug" TIMEOUT 120)
endif()

if(VDE_CORPUS_GATE_PYTHON)
    add_test(NAME VDE_CorpusGateSelfTest
        COMMAND "${VDE_CORPUS_GATE_PYTHON}"
            "${CMAKE_SOURCE_DIR}/tools/vde_corpus_gate.py" --self-test)
    set_tests_properties(VDE_CorpusGateSelfTest PROPERTIES
        LABELS "corpus;debug" TIMEOUT 120)

    set(_vde_corpus_has_files FALSE)
    foreach(_vde_corpus_dir IN ITEMS "${VDE_REAL_CORPUS_DIR}" "${VDE_REALFILE_DIR}")
        if(EXISTS "${_vde_corpus_dir}")
            file(GLOB_RECURSE _vde_corpus_files "${_vde_corpus_dir}/*")
            if(_vde_corpus_files)
                set(_vde_corpus_has_files TRUE)
            endif()
        endif()
    endforeach()
    option(VDE_ENABLE_HEAVY_CORPUS_TESTS
    "Run heavy real-corpus CTest gates (nightly/专用机)" OFF)
    if(_vde_corpus_has_files AND VDE_ENABLE_HEAVY_CORPUS_TESTS)
        add_test(NAME VDE_CorpusConfigGate
            COMMAND "${VDE_CORPUS_GATE_PYTHON}"
                "${CMAKE_SOURCE_DIR}/tools/vde_corpus_gate.py"
                --build-dir "${CMAKE_BINARY_DIR}")
        set_tests_properties(VDE_CorpusConfigGate PROPERTIES
            LABELS "corpus;slow" TIMEOUT 900)
    else()
        message(STATUS "VDE corpus gate: configured dirs empty/missing; only synthetic self-test registered")
    endif()
else()
    message(STATUS "VDE corpus gate: Python3 not found; corpus gate tests skipped")
endif()
