cmake_minimum_required(VERSION 3.30)

# Force gcc/g++ on Linux (must be before project())
if (UNIX AND NOT APPLE)
    set(CMAKE_C_COMPILER gcc)
    set(CMAKE_CXX_COMPILER g++)
endif()

project(hgraph_cpp_engine)

if (NOT SKBUILD)
    message(WARNING "\
  This CMake file is meant to be executed using 'scikit-build'. Running
  it directly will almost certainly not produce the desired result. If
  you are a user trying to install this package, please use the command
  below, which will install all necessary build dependencies, compile
  the package in an isolated environment, and then install it.
  =====================================================================
   $ pip install .
  =====================================================================
  If you are a software developer, and this is your own package, then
  it is usually much more efficient to install the build dependencies
  in your environment once and use the following command that avoids
  a costly creation of a new virtual environment at every compilation:
  =====================================================================
   $ pip install nanobind scikit-build-core[pyproject]
   $ pip install --no-build-isolation -ve .
  =====================================================================
  You may optionally add -Ceditable.rebuild=true to auto-rebuild when
  the package is imported. Otherwise, you need to re-run the above
  after editing C++ files.")
endif()

set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

if (UNIX)
    set(CMAKE_CXX_FLAGS_RELEASE "-g -O3")
    set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-g -O3 -DNDEBUG")
    set(CMAKE_CXX_FLAGS_DEBUG "-g -v") # -fsanitize=address")
    set(CMAKE_CXX_FLAGS "-Wall")
elseif (MSVC)
    # MSVC optimization flags for Windows
    set(CMAKE_CXX_FLAGS_RELEASE "/O2 /Zi /DNDEBUG")
    set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "/O2 /Zi /DNDEBUG")
    set(CMAKE_CXX_FLAGS_DEBUG "/Zi /Od")
    set(CMAKE_CXX_FLAGS "/W3 /EHsc")
endif ()

if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    # Set properties specific to macOS
    # Check for Apple Silicon (ARM architecture)
    if (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "arm64")
        message(STATUS "Configuring for Apple Silicon (ARM64)")
        include_directories(/opt/homebrew/include)
        link_directories(/opt/homebrew/lib)
    else (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "arm64")
        message(STATUS "Configuring for Intel (x86_64)")
        include_directories(/usr/local/include)
        link_directories(/usr/local/lib)
    endif (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "arm64")
endif (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

#find_package(spdlog CONFIG REQUIRED)

# Set Python executable to .venv if available
# Use this is you have having issues finding the nanobind code
#if(EXISTS "${CMAKE_SOURCE_DIR}/.venv/bin/python")
#    set(Python_EXECUTABLE "${CMAKE_SOURCE_DIR}/.venv/bin/python")
#endif()

find_package(Python 3.12 REQUIRED COMPONENTS Interpreter Development.Module)
include_directories(${Python3_INCLUDE_DIRS})

#find_package(tsl-robin-map CONFIG REQUIRED)
execute_process(
        COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
        OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE nanobind_ROOT)
find_package(nanobind CONFIG REQUIRED)
include_directories(${NB_DIR}/include)
message(STATUS "Nanobind DIR: ${NB_DIR}/include")
#find_package(Boost REQUIRED)
find_package(Threads)

#find_package(immer CONFIG REQUIRED)

# Prefer package config (Conan / system). If not found, fetch them.
message(STATUS "CMAKE_PREFIX_PATH: ${CMAKE_PREFIX_PATH}")
find_package(fmt CONFIG QUIET)
if (NOT fmt_FOUND)
    message(STATUS "fmt not found via find_package, using FetchContent")
    include(FetchContent)
    FetchContent_Declare(fmt GIT_REPOSITORY https://github.com/fmtlib/fmt.git GIT_TAG 10.1.0)
    FetchContent_MakeAvailable(fmt)
else()
    message(STATUS "Found fmt via Conan/system: ${fmt_DIR}")
endif()

find_package(Backward CONFIG QUIET)
if (NOT Backward_FOUND)
    message(STATUS "Backward not found via find_package, using FetchContent")
    include(FetchContent)
    # Set minimum policy version to allow backward-cpp to work with CMake 4.x
    set(CMAKE_POLICY_VERSION_MINIMUM 3.5)
    FetchContent_Declare(backward GIT_REPOSITORY https://github.com/bombela/backward-cpp.git GIT_TAG v1.6)
    set(BACKWARD_ENABLE ON CACHE BOOL "Enable backward" FORCE)
    FetchContent_MakeAvailable(backward)
    # Create an alias to match the expected target name
    if(TARGET backward)
        add_library(Backward::Backward ALIAS backward)
    endif()
else()
    message(STATUS "Found Backward via Conan/system: ${Backward_DIR}")
endif()

if (EXISTS "${CMAKE_SOURCE_DIR}/.git")
    execute_process(
            COMMAND git rev-parse --abbrev-ref HEAD
            WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
            OUTPUT_VARIABLE GIT_BRANCH
            OUTPUT_STRIP_TRAILING_WHITESPACE
    )
    execute_process(
            COMMAND git log -1 --format=%H
            WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
            OUTPUT_VARIABLE GIT_COMMIT_HASH
            OUTPUT_STRIP_TRAILING_WHITESPACE
    )
    execute_process(
            COMMAND git log -1 --format=%cD
            WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
            OUTPUT_VARIABLE GIT_COMMIT_DATE
            OUTPUT_STRIP_TRAILING_WHITESPACE
    )
else (EXISTS "${CMAKE_SOURCE_DIR}/.git")
    set(GIT_BRANCH "")
    set(GIT_COMMIT_HASH "")
    set(GIT_COMMIT_DATE "")
endif (EXISTS "${CMAKE_SOURCE_DIR}/.git")

message(STATUS "Git current branch: ${GIT_BRANCH}")
message(STATUS "Git commit hash: ${GIT_COMMIT_HASH}")
message(STATUS "Git commit date: ${GIT_COMMIT_DATE}")

message(STATUS "Generating version.h")
configure_file(
        ${CMAKE_SOURCE_DIR}/include/hgraph/version.h.in
        ${CMAKE_BINARY_DIR}/generated/version.h
)

include_directories(include)

set(HGRAPH_INCLUDES

        include/hgraph/hgraph_forward_declarations.h

        include/hgraph/builders/builder.h
        include/hgraph/builders/graph_builder.h
        include/hgraph/builders/input_builder.h
        include/hgraph/builders/node_builder.h
        include/hgraph/builders/output_builder.h

        include/hgraph/nodes/base_python_node.h
        include/hgraph/nodes/component_node.h
        include/hgraph/nodes/last_value_pull_node.h
        include/hgraph/nodes/mesh_node.h
        include/hgraph/nodes/nest_graph_node.h
        include/hgraph/nodes/nested_evaluation_engine.h
        include/hgraph/nodes/nested_node.h
        include/hgraph/nodes/python_node.h
        include/hgraph/nodes/non_associative_reduce_node.h
        include/hgraph/nodes/python_generator_node.h
        include/hgraph/nodes/push_queue_node.h
        include/hgraph/nodes/reduce_node.h
        include/hgraph/nodes/switch_node.h
        include/hgraph/nodes/try_except_node.h
        include/hgraph/nodes/tsd_map_node.h

        include/hgraph/runtime/evaluation_context.h
        include/hgraph/runtime/evaluation_engine.h
        include/hgraph/runtime/graph_executor.h
        include/hgraph/runtime/record_replay.h

        include/hgraph/types/constants.h
        include/hgraph/types/error_type.h
        include/hgraph/types/feature_extension.h
        include/hgraph/types/graph.h
        include/hgraph/types/node.h
        include/hgraph/types/ref.h
        include/hgraph/types/scalar_types.h
        include/hgraph/types/schema_type.h
        include/hgraph/types/time_series_type.h
        include/hgraph/types/traits.h
        include/hgraph/types/ts.h
        include/hgraph/types/ts_signal.h
        include/hgraph/types/tsd.h
        include/hgraph/types/tss.h
        include/hgraph/types/ts_indexed.h
        include/hgraph/types/tsb.h
        include/hgraph/types/tsl.h

        include/hgraph/python/chrono.h
        include/hgraph/python/format.h
        include/hgraph/python/global_state.h
        include/hgraph/python/global_keys.h
        include/hgraph/python/hashable.h
        include/hgraph/python/nb_types_ext.h
        include/hgraph/python/reference_wrapper.h

        include/hgraph/util/date_time.h
        include/hgraph/util/lifecycle.h
        include/hgraph/util/reference_count_subscriber.h
        include/hgraph/util/sender_receiver_state.h
        include/hgraph/util/stack_trace.h
        include/hgraph/util/string_utils.h

        include/hgraph/hgraph_export.h
)

list(TRANSFORM HGRAPH_INCLUDES PREPEND "${CMAKE_SOURCE_DIR}/")

list(APPEND HGRAPH_INCLUDES ${CMAKE_BINARY_DIR}/generated/version.h)

add_subdirectory(src/cpp)
#add_subdirectory(tests/cpp)

macro(dump_cmake_variables)
    message(STATUS "================ All cmake variables ==================")
    get_cmake_property(_variableNames VARIABLES)
    foreach (_variableName ${_variableNames})
        message(STATUS "${_variableName}=${${_variableName}}")
    endforeach ()
    message(STATUS "================ All cmake variables DONE ============")
endmacro()


set(DUMP_CMAKE_VARIABLES ON)

if (DUMP_CMAKE_VARIABLES)
    dump_cmake_variables()
endif ()