cmake_minimum_required(VERSION 3.16)
project(Nova64 VERSION 1.0.0 LANGUAGES C)

option(BUILD_CORE "Build the Nova64 native core library" ON)
option(BUILD_ESP32 "Build the ESP32 firmware project" OFF)
option(BUILD_SIMULATOR "Build the C# simulator project" OFF)
set(SIMULATOR_PROJECT "simulator/Nova64Simulator.csproj" CACHE PATH "Path to the C# simulator .csproj or .sln relative to repository root")

set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

if(BUILD_CORE)
    add_subdirectory(core)
endif()

if(BUILD_ESP32)
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/esp32/CMakeLists.txt")
        add_subdirectory(esp32)
    else()
        message(WARNING "BUILD_ESP32=ON but esp32/CMakeLists.txt is missing.")
    endif()
endif()

if(BUILD_SIMULATOR)
    find_program(DOTNET_EXECUTABLE dotnet)
    if(NOT DOTNET_EXECUTABLE)
        message(FATAL_ERROR "BUILD_SIMULATOR requires the .NET SDK. Install dotnet or disable BUILD_SIMULATOR.")
    endif()

    if(NOT SIMULATOR_PROJECT)
        message(FATAL_ERROR "BUILD_SIMULATOR=ON requires SIMULATOR_PROJECT to point to the simulator .csproj or .sln relative to the repository root.")
    endif()

    add_custom_target(simulator ALL
        COMMAND "${DOTNET_EXECUTABLE}" build "${CMAKE_CURRENT_SOURCE_DIR}/${SIMULATOR_PROJECT}" /p:NativeLibDir="${CMAKE_LIBRARY_OUTPUT_DIRECTORY}"
        WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/simulator"
        COMMENT "Building C# simulator project"
    )

    if(BUILD_CORE)
        add_dependencies(simulator nova64_core)
    endif()
endif()
