# cpp/CMakeLists.txt — Unified C++ build for BioNetGen core + NFSim

# WO-3b: NFSIM_USE_EXPRTK and the ExprTk include path are gone. NFsim shares
# the platform expression engine; nfsim_core links bng_parser for parsing and
# bng_ast for evaluation.


# =============================================================================
# nauty (graph isomorphism)
# =============================================================================
file(GLOB NAUTY_SOURCES "nauty/*.c")
add_library(nauty STATIC ${NAUTY_SOURCES})
target_include_directories(nauty PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/nauty)

# =============================================================================
# bng_units (compile-time physical-unit algebra)
# =============================================================================
add_library(bng_units STATIC units/Unit.cpp)
target_include_directories(bng_units PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}/units
)

# =============================================================================
# bng_core (pattern graph, node, state, transformations)
# =============================================================================
file(GLOB BNG_CORE_SOURCES "core/*.cpp")
list(FILTER BNG_CORE_SOURCES EXCLUDE REGEX ".*_wrap\\.cxx")
add_library(bng_core STATIC ${BNG_CORE_SOURCES})
target_include_directories(bng_core PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}/core
)
target_link_libraries(bng_core PUBLIC nauty)

# =============================================================================
# bng_ast (model AST nodes)
# =============================================================================
file(GLOB BNG_AST_SOURCES CONFIGURE_DEPENDS "ast/*.cpp")
add_library(bng_ast STATIC ${BNG_AST_SOURCES})
target_include_directories(bng_ast PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}/ast
    ${CMAKE_CURRENT_SOURCE_DIR}/parser/generated
    ${CMAKE_CURRENT_SOURCE_DIR}/parser
    ${antlr4_runtime_SOURCE_DIR}/runtime/Cpp/runtime/src
)
target_link_libraries(bng_ast PUBLIC bng_core antlr4_static bng_units)
if(MSVC)
    target_compile_definitions(bng_ast PRIVATE _USE_MATH_DEFINES)
endif()

# =============================================================================
# bng_parser (ANTLR4 BNGL parser)
# =============================================================================
set(ANTLR_GEN_DIR ${CMAKE_CURRENT_SOURCE_DIR}/parser/generated)
add_library(bng_parser STATIC
    ${ANTLR_GEN_DIR}/BNGLexer.cpp
    ${ANTLR_GEN_DIR}/BNGParser.cpp
    ${ANTLR_GEN_DIR}/BNGParserBaseVisitor.cpp
    ${ANTLR_GEN_DIR}/BNGParserVisitor.cpp
    parser/BNGAstVisitor.cpp
    parser/PatternGraphBuilder.cpp
    parser/ThermoSourceNormalization.cpp
    parser/ThermoModelFinalize.cpp
)
target_include_directories(bng_parser PUBLIC
    ${ANTLR_GEN_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}/parser
    ${antlr4_runtime_SOURCE_DIR}/runtime/Cpp/runtime/src
)
target_link_libraries(bng_parser PUBLIC antlr4_static bng_ast)

# Execution-facing metadata; no NFsim runtime path is switched by this library.
add_library(bng_compile STATIC
    compile/Capabilities.cpp
    compile/Document.cpp
    compile/PatternDescriptor.cpp
    compile/PatternLowering.cpp
    compile/LegacyAstLowering.cpp
    compile/SymbolTable.cpp
    compile/UnitAnalysis.cpp
    compile/energy/EnergyDeltaPlan.cpp
    compile/energy/ThermodynamicConstraints.cpp
    compile/energy/BarrierTable.cpp
    compile/energy/BarrierCompiler.cpp
    compile/energy/DrivenEnergy.cpp
    compile/CompiledRateLaw.cpp
    compile/CompiledRule.cpp
    compile/CompiledModel.cpp
    compile/TotalRate.cpp)
target_link_libraries(bng_compile PUBLIC bng_ast PRIVATE bng_parser)

# =============================================================================
# bng_engine (simulators, I/O writers, actions, console)
# =============================================================================
add_library(bng_engine STATIC
    engine/NetworkGenerator.cpp
    engine/NetworkRulePlan.cpp
    engine/LegacyNetworkRuleKernel.cpp
    engine/ObservableProjection.cpp
    engine/OdeIntegrator.cpp
    engine/EventClock.cpp
    engine/BatchSsa.cpp
    engine/gpu/GpuSsaBackend.cpp
    engine/gpu/NfnextGpuBackend.cpp
    engine/PlaSimulator.cpp
    engine/PsaSimulator.cpp
    engine/HybridModelGenerator.cpp
    io/NetWriter.cpp
    io/NetReader.cpp
    io/SbmlReader.cpp
    io/SbmlUnitWriter.cpp
    io/XmlWriter.cpp
    io/BnglWriter.cpp
    io/EnergyExportGuard.cpp
    io/SbmlWriter.cpp
    io/SbmlMultiWriter.cpp
    io/MatlabWriter.cpp
    io/CppExportWriter.cpp
    io/PythonExportWriter.cpp
    io/ContactMapWriter.cpp
    io/MexWriter.cpp
    io/RegulatoryGraphWriter.cpp
    io/ReactionNetworkGraphWriter.cpp
    io/RulevizPatternWriter.cpp
    io/RulevizOperationWriter.cpp
    io/ProcessGraphWriter.cpp
    io/RuleInfluenceGraphWriter.cpp
    io/LatexWriter.cpp
    io/MdlWriter.cpp
    io/SscWriter.cpp
    actions/ActionDispatch.cpp
    console/Console.cpp
    cli/BatchRunner.cpp
)
add_library(bng_finite_backend STATIC
    engine/FiniteBackend.cpp
)
target_include_directories(bng_finite_backend PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${ANTLR_GEN_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}/parser
    ${antlr4_runtime_SOURCE_DIR}/runtime/Cpp/runtime/src
    ${sundials_SOURCE_DIR}/include
    ${sundials_BINARY_DIR}/include
)
target_link_libraries(bng_finite_backend PUBLIC bng_engine bng_parser bng_ast)
target_sources(bng_engine PRIVATE engine/BngsimAdapter.cpp)
if(BUILD_BNGSIM_ADAPTER)
    target_sources(bng_finite_backend PRIVATE engine/BngsimBackend.cpp)
    target_link_libraries(bng_finite_backend PUBLIC bngsim_external)
endif()

# bng_engine always links the finite-backend dispatch (compile-safe without BNGsim)
target_link_libraries(bng_engine PUBLIC bng_finite_backend)
target_include_directories(bng_engine PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}/nfsim/NFinput/TinyXML
    ${ANTLR_GEN_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}/parser
    ${antlr4_runtime_SOURCE_DIR}/runtime/Cpp/runtime/src
    ${sundials_SOURCE_DIR}/include
    ${sundials_BINARY_DIR}/include
)
target_link_libraries(bng_engine PUBLIC
    bng_parser
    bng_ast
    bng_compile
    bng_core
    antlr4_static
    sundials_cvode_static
    sundials_ida_static
    sundials_nvecserial_static
    sundials_sunnonlinsolfixedpoint_static
    sundials_sunlinsoldense_static
    sundials_sunlinsolspgmr_static
    sundials_sunmatrixdense_static
    Threads::Threads
)
target_compile_definitions(bng_engine PUBLIC BNG_CPP_SOURCE_DIR="${CMAKE_SOURCE_DIR}")
target_compile_definitions(bng_engine PUBLIC TIXML_USE_STL)
if(BUILD_BNGSIM_ADAPTER)
    target_compile_definitions(bng_engine PUBLIC BNG3_HAS_BNGSIM_ADAPTER=1)
    target_link_libraries(bng_engine PUBLIC bngsim_external)
endif()
# =============================================================================
# Batched SSA GPU backends
#
# The batched direct-SSA path is backend agnostic: engine/gpu/GpuSsaBackend.cpp
# picks whichever backend was compiled in and has a usable device, and callers
# fall back to the CPU pool otherwise. Metal ships on Apple platforms, CUDA is
# compiled when a CUDA compiler is available.
# =============================================================================
set(BNG3_ENABLE_METAL "AUTO" CACHE STRING
    "Build the Metal batch-SSA backend (AUTO/ON/OFF)")
set(BNG3_ENABLE_CUDA "AUTO" CACHE STRING
    "Build the CUDA batch-SSA backend (AUTO/ON/OFF)")
set_property(CACHE BNG3_ENABLE_METAL PROPERTY STRINGS AUTO ON OFF)
set_property(CACHE BNG3_ENABLE_CUDA PROPERTY STRINGS AUTO ON OFF)

set(BNG3_GPU_BACKEND_SOURCES "")
set(BNG3_GPU_BACKEND_NAMES "")
set(BNG3_GPU_BACKEND_DEFINES "")
if(APPLE AND NOT BNG3_ENABLE_METAL STREQUAL "OFF")
    list(APPEND BNG3_GPU_BACKEND_SOURCES engine/gpu/MetalSsaBackend.mm)
    list(APPEND BNG3_GPU_BACKEND_SOURCES engine/gpu/NfnextMetalBackend.mm)
    list(APPEND BNG3_GPU_BACKEND_NAMES "metal")
    list(APPEND BNG3_GPU_BACKEND_DEFINES BNG3_HAS_METAL=1)
    target_link_libraries(bng_engine PUBLIC "-framework Metal" "-framework Foundation")
endif()

if(NOT BNG3_ENABLE_CUDA STREQUAL "OFF")
    include(CheckLanguage)
    check_language(CUDA)
    if(BNG3_ENABLE_CUDA STREQUAL "ON" AND NOT CMAKE_CUDA_COMPILER)
        message(FATAL_ERROR
            "BNG3_ENABLE_CUDA=ON but no CUDA compiler was found. Install the CUDA "
            "toolkit or configure with -DBNG3_ENABLE_CUDA=OFF.")
    endif()
    if(CMAKE_CUDA_COMPILER)
        if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES)
            # No GPU is visible at configure time on build machines, so probe a
            # fixed list that covers Volta and newer and rely on PTX JIT for
            # anything newer. Override with -DCMAKE_CUDA_ARCHITECTURES=... to
            # target a specific device.
            set(CMAKE_CUDA_ARCHITECTURES "70;80" CACHE STRING
                "CUDA architectures for the batch-SSA kernel")
        endif()
        enable_language(CUDA)
        # The .cu translation unit calls the CUDA runtime API (cudaMalloc /
        # cudaFree / cudaMemcpy). Without an explicit link the final binaries
        # fail with undefined references once the backend really compiles.
        find_package(CUDAToolkit REQUIRED)
        target_link_libraries(bng_engine PUBLIC CUDA::cudart)
        set_target_properties(bng_engine PROPERTIES CUDA_ARCHITECTURES
            "${CMAKE_CUDA_ARCHITECTURES}")
        list(APPEND BNG3_GPU_BACKEND_SOURCES engine/gpu/CudaSsaBackend.cu)
        list(APPEND BNG3_GPU_BACKEND_SOURCES engine/gpu/NfnextCudaBackend.cu)
        list(APPEND BNG3_GPU_BACKEND_NAMES "cuda")
        list(APPEND BNG3_GPU_BACKEND_DEFINES BNG3_HAS_CUDA=1)
    elseif(NOT BNG3_ENABLE_CUDA STREQUAL "AUTO")
        message(STATUS "BNG3 batch SSA: no CUDA compiler found, CUDA backend disabled")
    endif()
endif()

if(BNG3_GPU_BACKEND_SOURCES)
    target_sources(bng_engine PRIVATE ${BNG3_GPU_BACKEND_SOURCES})
    target_compile_definitions(bng_engine PRIVATE ${BNG3_GPU_BACKEND_DEFINES})
    string(REPLACE ";" ", " BNG3_GPU_BACKEND_NAMES_TEXT "${BNG3_GPU_BACKEND_NAMES}")
    message(STATUS "BNG3 batch SSA GPU backends: ${BNG3_GPU_BACKEND_NAMES_TEXT}")
endif()

# =============================================================================
# nfsim_core (Network-free stochastic simulator)
# =============================================================================
set(NFSIM_DIR ${CMAKE_CURRENT_SOURCE_DIR}/nfsim)

file(GLOB NFSIM_CORE_SRC "${NFSIM_DIR}/NFcore/*.cpp")
list(FILTER NFSIM_CORE_SRC EXCLUDE REGEX ".*/profile\\.cpp$")
file(GLOB NFSIM_CORE_MOLLISTS "${NFSIM_DIR}/NFcore/moleculeLists/*.cpp")
file(GLOB NFSIM_CORE_RXNSEL "${NFSIM_DIR}/NFcore/reactionSelector/*.cpp")
file(GLOB NFSIM_INPUT_SRC "${NFSIM_DIR}/NFinput/*.cpp")
file(GLOB NFSIM_INPUT_XML "${NFSIM_DIR}/NFinput/TinyXML/*.cpp")
file(GLOB NFSIM_RXN_SRC "${NFSIM_DIR}/NFreactions/*.cpp")
file(GLOB NFSIM_RXN_TRANS "${NFSIM_DIR}/NFreactions/transformations/*.cpp")
file(GLOB NFSIM_RXN_RXN "${NFSIM_DIR}/NFreactions/reactions/*.cpp")
file(GLOB NFSIM_RXN_RLISTS "${NFSIM_DIR}/NFreactions/reactantLists/*.cpp")
file(GLOB NFSIM_RXN_MAPS "${NFSIM_DIR}/NFreactions/mappings/*.cpp")
file(GLOB NFSIM_FUNC_SRC "${NFSIM_DIR}/NFfunction/*.cpp")
# muParser and ExprTk both removed: nfsim_funcparser.h is now a thin mu::Parser
# interface over the shared bng::ast::Expression evaluator (WO-3).
file(GLOB NFSIM_OUTPUT_SRC "${NFSIM_DIR}/NFoutput/*.cpp")
file(GLOB NFSIM_SCHED_SRC "${NFSIM_DIR}/NFscheduler/*.cpp")
file(GLOB NFSIM_UTIL_SRC "${NFSIM_DIR}/NFutil/*.cpp")
file(GLOB NFSIM_UTIL_MTRAND "${NFSIM_DIR}/NFutil/MTrand/*.cpp")
# WO-1b: nfsim_core no longer compiles its own nauty copy. It links the shared
# `nauty` target instead (see cpp/nauty/README.md).

# Exclude NFsim.cpp (main) and NFtest sources from the library
set(NFSIM_LIB_SOURCES
    ${NFSIM_CORE_SRC}
    ${NFSIM_DIR}/NFcore/profile.cpp
    ${NFSIM_CORE_MOLLISTS}
    ${NFSIM_CORE_RXNSEL}
    ${NFSIM_INPUT_SRC}
    ${NFSIM_INPUT_XML}
    ${NFSIM_RXN_SRC}
    ${NFSIM_RXN_TRANS}
    ${NFSIM_RXN_RXN}
    ${NFSIM_RXN_RLISTS}
    ${NFSIM_RXN_MAPS}
    ${NFSIM_FUNC_SRC}
    ${NFSIM_OUTPUT_SRC}
    ${NFSIM_SCHED_SRC}
    ${NFSIM_UTIL_SRC}
    ${NFSIM_UTIL_MTRAND}
)

# Remove NFsim.cpp (contains main())
list(FILTER NFSIM_LIB_SOURCES EXCLUDE REGEX ".*/NFsim\\.cpp$")

add_library(nfsim_core STATIC ${NFSIM_LIB_SOURCES})
target_include_directories(nfsim_core PUBLIC
    ${NFSIM_DIR}
    ${NFSIM_DIR}/NFcore
    ${NFSIM_DIR}/NFcore/moleculeLists
    ${NFSIM_DIR}/NFcore/reactionSelector
    ${NFSIM_DIR}/NFinput
    ${NFSIM_DIR}/NFinput/TinyXML
    ${NFSIM_DIR}/NFreactions
    ${NFSIM_DIR}/NFreactions/transformations
    ${NFSIM_DIR}/NFreactions/reactions
    ${NFSIM_DIR}/NFreactions/reactantLists
    ${NFSIM_DIR}/NFreactions/mappings
    ${NFSIM_DIR}/NFfunction
    ${NFSIM_DIR}/NFoutput
    ${NFSIM_DIR}/NFscheduler
    ${NFSIM_DIR}/NFutil
    ${NFSIM_DIR}/NFutil/MTrand
    # Canonical labeling comes from the one shared nauty build. Propagated
    # PUBLIC because NFcore.hh-consuming targets transitively include it.
    $<TARGET_PROPERTY:nauty,INTERFACE_INCLUDE_DIRECTORIES>
    # Allow NFinput_fromModel.cpp to include ast/Model.hpp and core/ headers
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}/ast
    ${CMAKE_CURRENT_SOURCE_DIR}/core
    ${CMAKE_CURRENT_SOURCE_DIR}/parser
    ${CMAKE_CURRENT_SOURCE_DIR}/parser/generated
)
target_compile_definitions(nfsim_core PUBLIC TIXML_USE_STL)
target_link_libraries(nfsim_core PUBLIC bng_parser bng_compile nauty)
if(MSVC)
    target_compile_options(nfsim_core PRIVATE /bigobj)
else()
    target_compile_options(nfsim_core PRIVATE -Wno-deprecated-declarations)
    if(MINGW)
        target_compile_options(nfsim_core PRIVATE -Wa,-mbig-obj)
    endif()
endif()

# Apply the guarded Release IPO setting to the embedded NFsim implementation.
# Final targets also need the property so the linker can consume the NFsim
# bitcode when it is linked into the unified CLI, Python extension, or legacy
# standalone executable.
if(NFSIM_IPO_SUPPORTED)
    set_property(TARGET nfsim_core
        PROPERTY INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE)
endif()

# =============================================================================
# bionetgen_core — combined static library for all C++ components
# =============================================================================
# Archived NFcore2 prototype engine (legacy/nfcore2). Not linked into
# bionetgen_core or released artifacts; built only when BUILD_TESTS=ON to
# preserve historical parity and architecture-contract fixtures (#149).
if(BUILD_TESTS)
    add_library(bng_nfcore2 STATIC
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/compiled_model.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/engine.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/executable_model.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/legacy_bridge.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/driver.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/matcher.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/model_image.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/nfsim_adapter_contract.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/nfsim_system_reader.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/nfsim_native_reader.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/seed.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/nfsim_transform_decoder.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/rule_compiler.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/scaffold.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/scheduler.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/shadow.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/simulation_state.cpp
        ${CMAKE_SOURCE_DIR}/legacy/nfcore2/transform.cpp
    )
    target_include_directories(bng_nfcore2 PUBLIC ${CMAKE_SOURCE_DIR}/legacy/nfcore2)
    target_link_libraries(bng_nfcore2 PUBLIC nfsim_core)
endif()
find_package(Threads REQUIRED)
add_library(bng_nfnext STATIC
    nfnext/src/cache.cpp
    nfnext/src/cache_v2.cpp
    nfnext/src/canonical.cpp
    nfnext/src/compiler.cpp
    nfnext/src/family_compiler.cpp
    nfnext/src/from_bng.cpp
    nfnext/src/generic_matcher.cpp
    nfnext/src/generic_state.cpp
    nfnext/src/lattice.cpp
    nfnext/src/nfir.cpp
    nfnext/src/rule_family.cpp
    nfnext/src/trajectory.cpp
    nfnext/src/transformation.cpp
    nfnext/src/validator.cpp
)
target_include_directories(bng_nfnext PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/nfnext/include)
target_link_libraries(bng_nfnext PUBLIC Threads::Threads bng_compile)
target_include_directories(bng_engine PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/nfnext/include)
target_link_libraries(bng_engine PUBLIC bng_nfnext)

add_library(bionetgen_core INTERFACE)
target_link_libraries(bionetgen_core INTERFACE
    bng_engine
    bng_parser
    bng_ast
    bng_compile
    bng_nfnext
    bng_core
    nauty
    nfsim_core
)

# =============================================================================
# bng_cpp executable (CLI)
# =============================================================================
if(BUILD_CLI)
    add_executable(bng_cpp main.cpp)
    target_link_libraries(bng_cpp PRIVATE bionetgen_core)
    target_compile_definitions(bng_cpp PRIVATE
        BNG_CPP_SOURCE_DIR="${CMAKE_SOURCE_DIR}"
        BNG3_VERSION_STRING="${BNG3_VERSION_STRING}"
    )
    if(NFSIM_IPO_SUPPORTED)
        set_property(TARGET bng_cpp
            PROPERTY INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE)
    endif()
endif()

# =============================================================================
# NFsim executable (optional, for backward compatibility)
# =============================================================================
if(BUILD_NFSIM_CLI)
    file(GLOB_RECURSE NFSIM_TEST_SRC CONFIGURE_DEPENDS
        "${NFSIM_DIR}/NFtest/*.cpp"
    )
    add_executable(NFsim ${NFSIM_DIR}/NFsim.cpp ${NFSIM_TEST_SRC})
    target_link_libraries(NFsim PRIVATE nfsim_core)
    target_include_directories(NFsim PRIVATE
        ${NFSIM_DIR}/NFtest
        ${NFSIM_DIR}/NFtest/simple_system
        ${NFSIM_DIR}/NFtest/transcription
        ${NFSIM_DIR}/NFtest/tlbr
        ${NFSIM_DIR}/NFtest/agentcell
        ${NFSIM_DIR}/NFtest/agentcell/cell
    )
    target_compile_definitions(NFsim PRIVATE TIXML_USE_STL)
    if(NFSIM_IPO_SUPPORTED)
        set_property(TARGET NFsim
            PROPERTY INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE)
    endif()
endif()

# =============================================================================
# Python bindings (pybind11)
# =============================================================================
if(BUILD_PYTHON_BINDINGS)
    pybind11_add_module(_bionetgen_cpp
        bindings/module.cpp
        bindings/bind_model.cpp
        bindings/bind_bngir.cpp
        bindings/bind_compile_snapshot.cpp
        bindings/bind_parser.cpp
        bindings/bind_engine.cpp
        bindings/bind_nfsim.cpp
        bindings/bind_nfnext.cpp
        bindings/bind_io.cpp
        bindings/bind_viz.cpp
        bindings/bind_jax_ssa.cpp
        bindings/bind_graph_identity.cpp
    )
    target_link_libraries(_bionetgen_cpp PRIVATE bionetgen_core)
    # The extension links the C++ runtime dynamically, unlike the CLI
    # executables (see CMAKE_EXE_LINKER_FLAGS in the top-level CMakeLists).
    # Embedding a second copy of libstdc++ inside the module corrupts the
    # host process whenever another loaded library also brings in
    # libstdc++.so.6 -- SciPy's C++ extensions do exactly that. The two
    # runtimes end up with independent locale facet tables, so an
    # ostringstream dispatches a numeric format through the wrong facet and
    # the process segfaults. Observed on Linux/GCC as a crash in
    # bng::ast::Expression::toString() while inserting a double, with
    # std::codecvt<char16_t>::do_length called from
    # std::ostream::_M_insert<double> -- a call ostream cannot make without
    # the facet mix-up. Reproduced by tests/test_batch_ssa_statistical_parity.py
    # --mode cpu, which imports scipy.stats before generating a network.
    target_include_directories(_bionetgen_cpp PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}
        ${CMAKE_CURRENT_SOURCE_DIR}/ast
        ${CMAKE_CURRENT_SOURCE_DIR}/core
        ${CMAKE_CURRENT_SOURCE_DIR}/engine
        ${CMAKE_CURRENT_SOURCE_DIR}/io
        ${CMAKE_CURRENT_SOURCE_DIR}/actions
        ${CMAKE_CURRENT_SOURCE_DIR}/parser
        ${CMAKE_CURRENT_SOURCE_DIR}/parser/generated
        ${NFSIM_DIR}
        ${NFSIM_DIR}/NFcore
        ${NFSIM_DIR}/NFinput
        ${antlr4_runtime_SOURCE_DIR}/runtime/Cpp/runtime/src
        ${sundials_SOURCE_DIR}/include
        ${sundials_BINARY_DIR}/include
    )
    target_compile_definitions(_bionetgen_cpp PRIVATE TIXML_USE_STL)
    if(UNIX AND NOT APPLE)
        # Hide symbols from statically linked archives (including bundled
        # SUNDIALS v7.6.0) so Linux ELF's flat symbol namespace cannot interpose
        # them onto dynamically loaded libraries such as libbngsim (which links
        # its own SUNDIALS v7.2.1) or libRoadRunner.
        target_link_options(_bionetgen_cpp PRIVATE -Wl,--exclude-libs,ALL)
    endif()

    if(NFSIM_IPO_SUPPORTED)
        set_property(TARGET _bionetgen_cpp
            PROPERTY INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE)
    endif()

    install(TARGETS _bionetgen_cpp DESTINATION bionetgen COMPONENT python)
endif()
