cmake_minimum_required(VERSION 3.21...3.31)  # 3.21: Gecode
project(${SKBUILD_PROJECT_NAME} VERSION ${SKBUILD_PROJECT_VERSION} LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Static Gecode and libminizinc are linked into the _core shared module.
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

# SKBUILD_SABI_COMPONENT is Development.SABIModule when wheel.py-api asks for
# abi3; without it nanobind's STABLE_ABI silently builds a version-specific .so.
find_package(Python REQUIRED COMPONENTS Interpreter Development.Module ${SKBUILD_SABI_COMPONENT})
find_package(nanobind CONFIG REQUIRED)

# --- Gecode -------------------------------------------------------------------
# Built once, used twice:
# - fzn-gecode, the full FlatZinc solver, run by MiniZinc as a child process.
#   libminizinc's linked Gecode backend is only an internal presolver.
# - linked into libminizinc, for solution checkers and the -O3+ presolver.
include(FetchContent)
set(MZN_GECODE_VERSION 6.6.0)  # matches thirdparty/libminizinc/vendor.lock
FetchContent_Declare(gecode
    URL https://github.com/Gecode/gecode/archive/refs/tags/release-${MZN_GECODE_VERSION}.tar.gz
    URL_HASH SHA256=de6441af2495aeb2b48766caaf51858ece69acf73cab3c39a96341f5b816a564)

# Static, so the executable depends only on the C++ runtime. MPFR is off to
# avoid an LGPL dependency; Gecode then rejects float trig/exp/log
# (docs/dev/mpfr-gecode.md).
set(GECODE_BUILD_SHARED OFF)
set(GECODE_BUILD_STATIC ON)
set(GECODE_ENABLE_QT OFF)
set(GECODE_ENABLE_MPFR OFF)
set(GECODE_ENABLE_CPPROFILER OFF)
set(GECODE_ENABLE_EXAMPLES OFF)
set(GECODE_INSTALL ON)  # export set required by libminizinc; not in the "python" install component
FetchContent_MakeAvailable(gecode)
set_property(DIRECTORY ${gecode_SOURCE_DIR} PROPERTY EXCLUDE_FROM_ALL TRUE)
# libminizinc's build-tree export() of mzn needs its Gecode dependencies in one.
export(EXPORT GecodeTargets NAMESPACE Gecode::
       FILE ${CMAKE_CURRENT_BINARY_DIR}/GecodeTargets.cmake)

# Wheel layout. MiniZinc resolves .msc paths against the .msc file's directory.
set(PKG_BIN_DIR pyminizinc/bin)
set(PKG_SHARE_DIR pyminizinc/share/minizinc)
set(PKG_SOLVER_DIR ${PKG_SHARE_DIR}/solvers)
cmake_path(RELATIVE_PATH PKG_BIN_DIR BASE_DIRECTORY ${PKG_SOLVER_DIR}
           OUTPUT_VARIABLE BIN_FROM_SOLVERDIR)

set(GECODE_VERSION ${MZN_GECODE_VERSION})
set(GECODE_MSC_MZNLIB_FROM_SOLVERDIR "../gecode")
# No .exe in .msc paths: on Windows MiniZinc tries each PATHEXT suffix.
set(GECODE_MSC_EXECUTABLE_FROM_SOLVERDIR "${BIN_FROM_SOLVERDIR}/fzn-gecode")
set(GECODE_MSC_STD_FLAGS [["-a", "-f", "-n", "-p", "-r", "-s", "-t"]])
configure_file(${gecode_SOURCE_DIR}/tools/flatzinc/gecode.msc.in
               ${CMAKE_CURRENT_BINARY_DIR}/gecode.msc @ONLY)

# --- libminizinc (static, linked into _core) ---------------------------------
set(MZN_DIR ${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/libminizinc)

# mimalloc's malloc override would replace the allocator of the whole Python
# process, so it stays off.
set(MZN_USE_MIMALLOC OFF CACHE BOOL "" FORCE)
set(MZN_BUNDLE_LIBRARIES OFF CACHE BOOL "" FORCE)
set(BUILD_SHARED_LIBS OFF)

# Host solver libraries would tie the wheel to the build machine. Solvers are
# reached through .msc configs (fzn, incl. the bundled Gecode) and dlopen
# plugins (HiGHS, CPLEX). Only the in-tree Gecode is linked, through a shim
# config, so a host Gecode is never picked up.
foreach(pkg Geas atlantis chuffed OsiCBC)
    set(CMAKE_DISABLE_FIND_PACKAGE_${pkg} ON)
endforeach()
set(Gecode_DIR ${CMAKE_CURRENT_SOURCE_DIR}/cmake/gecode-shim CACHE PATH "" FORCE)

add_subdirectory(${MZN_DIR} ${CMAKE_CURRENT_BINARY_DIR}/libminizinc EXCLUDE_FROM_ALL)

# --- Chuffed (fzn-chuffed executable, run by MiniZinc as a child process) ------
# Not linked into libminizinc: Chuffed keeps process-global solver state with no
# reset and calls exit() on root-level failure. Its CMake assumes it is the
# top-level project (include paths from CMAKE_SOURCE_DIR), so it is built as an
# external project. FetchContent only downloads it, at configure time, so the
# .msc template can be read here.
set(MZN_CHUFFED_VERSION 0.14.0)  # matches thirdparty/libminizinc/vendor.lock
FetchContent_Declare(chuffed
    URL https://github.com/chuffed/chuffed/archive/refs/tags/${MZN_CHUFFED_VERSION}.tar.gz
    URL_HASH SHA256=8f0da88d498bc610d894b784da59f87e1e7570fe017dd7249cc90f6ae81f1267
    SOURCE_SUBDIR no-cmake-here)  # no CMakeLists.txt there: populate, do not add
FetchContent_MakeAvailable(chuffed)

include(ExternalProject)
set(CHUFFED_BIN_DIR ${CMAKE_CURRENT_BINARY_DIR}/chuffed-bin)
set(CHUFFED_EXE ${CHUFFED_BIN_DIR}/fzn-chuffed${CMAKE_EXECUTABLE_SUFFIX})
set(chuffed_cache_args
    -DCMAKE_BUILD_TYPE:STRING=Release
    -DBUILD_SHARED_LIBS:BOOL=OFF
    -DCMAKE_RUNTIME_OUTPUT_DIRECTORY:PATH=${CHUFFED_BIN_DIR}
    -DCMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE:PATH=${CHUFFED_BIN_DIR})
# Same toolchain and targets as the wheel (cibuildwheel sets the macOS ones).
foreach(var CMAKE_C_COMPILER CMAKE_CXX_COMPILER CMAKE_OSX_ARCHITECTURES
            CMAKE_OSX_DEPLOYMENT_TARGET CMAKE_MSVC_RUNTIME_LIBRARY)
    if(NOT "${${var}}" STREQUAL "")
        list(APPEND chuffed_cache_args "-D${var}:STRING=${${var}}")
    endif()
endforeach()
ExternalProject_Add(chuffed_build
    SOURCE_DIR ${chuffed_SOURCE_DIR}
    CMAKE_CACHE_ARGS ${chuffed_cache_args}
    BUILD_COMMAND ${CMAKE_COMMAND} --build <BINARY_DIR> --config Release --target fzn-chuffed
    INSTALL_COMMAND ""
    BUILD_BYPRODUCTS ${CHUFFED_EXE})
if(CMAKE_STRIP AND NOT WIN32)
    # install --strip only covers install(TARGETS).
    ExternalProject_Add_Step(chuffed_build strip
        COMMAND ${CMAKE_STRIP} ${CHUFFED_EXE} DEPENDEES build)
endif()

string(REPLACE "." ";" chuffed_version_parts ${MZN_CHUFFED_VERSION})
list(GET chuffed_version_parts 0 chuffed_VERSION_MAJOR)
list(GET chuffed_version_parts 1 chuffed_VERSION_MINOR)
list(GET chuffed_version_parts 2 chuffed_VERSION_PATCH)
set(REL_INSTALL_BINARY "${BIN_FROM_SOLVERDIR}/fzn-chuffed")
configure_file(${chuffed_SOURCE_DIR}/chuffed.msc.in ${CMAKE_CURRENT_BINARY_DIR}/chuffed.msc)

# --- extension ---------------------------------------------------------------
# Stable ABI on Python >= 3.12: one wheel serves 3.12+, so CI builds the
# Python-independent libminizinc and Gecode once instead of per version.
nanobind_add_module(_core STABLE_ABI src/pyminizinc/_core.cpp)
target_link_libraries(_core PRIVATE mzn)
target_include_directories(_core SYSTEM PRIVATE
    ${MZN_DIR}/include
    ${CMAKE_CURRENT_BINARY_DIR}/libminizinc/include  # config.hh, bison output
    ${MZN_DIR}/lib/cached  # pre-generated parser headers, used without bison >= 3.4
)

if(MSVC)
    target_compile_options(_core PRIVATE /W4)
else()
    target_compile_options(_core PRIVATE -Wall -Wextra)
endif()

add_dependencies(_core fzn-gecode chuffed_build)  # EXCLUDE_FROM_ALL would skip fzn-gecode

# Only the "python" component is installed (see pyproject.toml), which skips
# libminizinc's own install rules.
install(TARGETS _core DESTINATION pyminizinc COMPONENT python)
install(DIRECTORY ${MZN_DIR}/share/minizinc/
        DESTINATION ${PKG_SHARE_DIR} COMPONENT python)
install(TARGETS fzn-gecode RUNTIME DESTINATION ${PKG_BIN_DIR} COMPONENT python)
install(DIRECTORY ${gecode_SOURCE_DIR}/gecode/flatzinc/mznlib/
        DESTINATION ${PKG_SHARE_DIR}/gecode COMPONENT python)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/gecode.msc
        DESTINATION ${PKG_SOLVER_DIR} COMPONENT python)
install(PROGRAMS ${CHUFFED_EXE} DESTINATION ${PKG_BIN_DIR} COMPONENT python)
install(DIRECTORY ${chuffed_SOURCE_DIR}/chuffed/flatzinc/mznlib/
        DESTINATION ${PKG_SHARE_DIR}/chuffed COMPONENT python)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/chuffed.msc
        DESTINATION ${PKG_SOLVER_DIR} COMPONENT python)
