#----------------------------------------------------------------------------
# Project setup
#----------------------------------------------------------------------------
cmake_minimum_required(VERSION 3.16...3.21)
project(ML_LWFA)

#----------------------------------------------------------------------------
# Geant4 and ROOT
#----------------------------------------------------------------------------
find_package(Geant4 REQUIRED gdml ui_all vis_all)
find_package(ROOT QUIET COMPONENTS Core RIO Tree Hist MathCore)
if(NOT ROOT_FOUND)
    message(STATUS "ML_LWFA: ROOT not found or disabled, example not built")
    return()
endif()

#----------------------------------------------------------------------------
# ONNX Runtime (optional)
#
# ONNX Runtime is an optional dependency used for ML-based particle generation.
# When disabled (default), the simulation falls back to the Geant4 General
# Particle Source (GPS). The macro parameter /ML_LWFA/gun/setStatusONNX
# controls which mode is active at runtime; setting it to 1 without having
# compiled with ONNX support will have no effect.
#
# Enable with:
#   cmake -DML_LWFA_USE_ONNX=ON -DOnnxRuntime_ROOT=/path/to/onnxruntime ..
#
# ONNX Runtime must be installed by the user (see https://onnxruntime.ai).
# It is searched in OnnxRuntime_ROOT first, then in the system paths.
# model2.onnx was tested with ONNX Runtime 1.17.1.
# Example (Linux x86_64):
#   wget https://github.com/microsoft/onnxruntime/releases/download/v1.17.1/onnxruntime-linux-x64-1.17.1.tgz
#   tar xzf onnxruntime-linux-x64-1.17.1.tgz
#----------------------------------------------------------------------------
option(ML_LWFA_USE_ONNX "Enable ONNX Runtime inference for ML-based particle gun" OFF)

if(ML_LWFA_USE_ONNX)
    find_library(OnnxRuntime_LIBRARY
        NAMES onnxruntime
        HINTS "${OnnxRuntime_ROOT}/lib"
        DOC "ONNX Runtime shared library"
    )
    find_path(OnnxRuntime_INCLUDE_DIR
        NAMES onnxruntime_cxx_api.h
        HINTS "${OnnxRuntime_ROOT}/include"
        DOC "ONNX Runtime include directory"
    )

    if(NOT OnnxRuntime_LIBRARY OR NOT OnnxRuntime_INCLUDE_DIR)
        message(FATAL_ERROR
            "ONNX Runtime not found. Install it (see https://onnxruntime.ai) "
            "and pass -DOnnxRuntime_ROOT=/path/to/onnxruntime to cmake.")
    endif()

    message(STATUS "OnnxRuntime library : ${OnnxRuntime_LIBRARY}")
    message(STATUS "OnnxRuntime include : ${OnnxRuntime_INCLUDE_DIR}")

    if(NOT TARGET OnnxRuntime)
        add_library(OnnxRuntime SHARED IMPORTED)
        set_property(TARGET OnnxRuntime PROPERTY IMPORTED_LOCATION "${OnnxRuntime_LIBRARY}")
        set_property(TARGET OnnxRuntime PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${OnnxRuntime_INCLUDE_DIR}")
    endif()
else()
    message(STATUS "ONNX Runtime disabled - building with GPS particle gun only")
    message(STATUS "To enable ONNX: cmake -DML_LWFA_USE_ONNX=ON -DOnnxRuntime_ROOT=/path/to/onnxruntime ..")
endif()


#----------------------------------------------------------------------------
# Output checker (used by CTest, see tests/ctests_examples/CMakeLists.txt)
#----------------------------------------------------------------------------
add_executable(ML_LWFA_check check_output.cc)
target_link_libraries(ML_LWFA_check PRIVATE ROOT::Core ROOT::RIO ROOT::Tree)

#----------------------------------------------------------------------------
# Sources and headers
#----------------------------------------------------------------------------
set(PROJECT_SRC
    src/Physics.cc
    src/Geometry.cc
    src/EventAction.cc
    src/GeometryMessenger.cc
    src/DetectorConstruction.cc
    src/PrimaryGeneratorAction.cc
    src/PrimaryGeneratorMessenger.cc
    src/RunAction.cc
    src/SteppingAction.cc
    src/ActionInitialization.cc
    src/MagneticField.cc
    src/OnnxInference.cc
    src/QuadrupoleUtils.cc
)

set(PROJECT_HEADER
    include/Physics.hh
    include/Geometry.hh
    include/EventAction.hh
    include/GeometryMessenger.hh
    include/DetectorConstruction.hh
    include/PrimaryGeneratorAction.hh
    include/PrimaryGeneratorMessenger.hh
    include/RunAction.hh
    include/SteppingAction.hh
    include/ActionInitialization.hh
    include/OnnxInference.hh
    include/OnnxParameters.hh
    include/MagneticField.hh
    include/QuadrupoleUtils.hh
)

#----------------------------------------------------------------------------
# Executable
#----------------------------------------------------------------------------
add_executable(ML_LWFA ML_LWFA.cc ${PROJECT_HEADER} ${PROJECT_SRC})

target_include_directories(ML_LWFA PRIVATE ${PROJECT_SOURCE_DIR}/include)

target_link_libraries(ML_LWFA PRIVATE
    ${Geant4_LIBRARIES}
    ROOT::Core ROOT::RIO ROOT::Tree ROOT::Hist ROOT::MathCore
)

if(ML_LWFA_USE_ONNX)
    target_compile_definitions(ML_LWFA PRIVATE ML_LWFA_USE_ONNX)
    target_link_libraries(ML_LWFA PRIVATE OnnxRuntime)
endif()

#----------------------------------------------------------------------------
# GDML geometry files (downloaded at configure time)
#----------------------------------------------------------------------------
set(ML_LWFA_GEOMETRY_FILENAME "ML_LWFA_geometry.tar.gz")
set(ML_LWFA_DATASETS_URL
    "https://cern.ch/geant4-data/datasets/examples/advanced/ML_LWFA/0/ML_LWFA_geometry.tar.gz")
set(ML_LWFA_HASH_MD5 "dfa129b1b9d4ca4d0a2e985309bc7e16")

message(STATUS "ML_LWFA: downloading GDML geometry files from ${ML_LWFA_DATASETS_URL}")

include(FetchContent)
FetchContent_Declare(
    ML_LWFA_GDML
    URL      ${ML_LWFA_DATASETS_URL}
    URL_HASH MD5=${ML_LWFA_HASH_MD5}
    DOWNLOAD_EXTRACT_TIMESTAMP TRUE
)
FetchContent_MakeAvailable(ML_LWFA_GDML)

message(STATUS "ML_LWFA: GDML geometry files available in ${ml_lwfa_gdml_SOURCE_DIR}")

#----------------------------------------------------------------------------
# Copy runtime resources (macros, ONNX model) into the
# build directory so the example can be run directly from there.
#----------------------------------------------------------------------------

set(ML_LWFA_RESOURCES
    macro_high_charge_divergence.mac
    macro_low_charge_divergence.mac
    vis.mac
    model2.onnx
)

foreach(_res ${ML_LWFA_RESOURCES})
    configure_file(
        ${PROJECT_SOURCE_DIR}/resources/${_res}
        ${PROJECT_BINARY_DIR}/${_res}
        COPYONLY
    )
endforeach()

# Copy the downloaded GDML files into <build>/gdml_models (next to the executable)
file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/gdml_models)
file(GLOB ML_LWFA_GDML_FILES ${ml_lwfa_gdml_SOURCE_DIR}/*.gdml)
list(LENGTH ML_LWFA_GDML_FILES ML_LWFA_GDML_COUNT)

if(ML_LWFA_GDML_COUNT EQUAL 0)
    message(FATAL_ERROR "ML_LWFA: no GDML file found in ${ml_lwfa_gdml_SOURCE_DIR}")
endif()

file(COPY ${ML_LWFA_GDML_FILES}
     DESTINATION ${PROJECT_BINARY_DIR}/gdml_models)
message(STATUS "ML_LWFA: ${ML_LWFA_GDML_COUNT} GDML files copied to ${PROJECT_BINARY_DIR}/gdml_models")
