include(AddMLIRPython)
add_compile_definitions(
  "MLIR_PYTHON_PACKAGE_PREFIX=${MLIR_PYTHON_PACKAGE_PREFIX}.")

declare_mlir_python_sources(FHEliumPythonSources)

declare_mlir_dialect_python_bindings(
  ADD_TO_PARENT
  FHEliumPythonSources
  ROOT_DIR
  "${CMAKE_CURRENT_SOURCE_DIR}/package"
  TD_FILE
  dialects/CKKSOps.td
  SOURCES
  dialects/fhelium_ckks.py
  DIALECT_NAME
  fhelium_ckks)

declare_mlir_dialect_python_bindings(
  ADD_TO_PARENT
  FHEliumPythonSources
  ROOT_DIR
  "${CMAKE_CURRENT_SOURCE_DIR}/package"
  TD_FILE
  dialects/LogicalOps.td
  SOURCES
  dialects/fhelium_logical.py
  DIALECT_NAME
  fhelium_logical)

declare_mlir_dialect_python_bindings(
  ADD_TO_PARENT
  FHEliumPythonSources
  ROOT_DIR
  "${CMAKE_CURRENT_SOURCE_DIR}/package"
  TD_FILE
  dialects/RNSOps.td
  SOURCES
  dialects/fhelium_rns.py
  DIALECT_NAME
  fhelium_rns)

declare_mlir_dialect_python_bindings(
  ADD_TO_PARENT
  FHEliumPythonSources
  ROOT_DIR
  "${CMAKE_CURRENT_SOURCE_DIR}/package"
  TD_FILE
  dialects/NTTOps.td
  SOURCES
  dialects/fhelium_ntt.py
  DIALECT_NAME
  fhelium_ntt)

declare_mlir_dialect_python_bindings(
  ADD_TO_PARENT
  FHEliumPythonSources
  ROOT_DIR
  "${CMAKE_CURRENT_SOURCE_DIR}/package"
  TD_FILE
  dialects/DistOps.td
  SOURCES
  dialects/fhelium_dist.py
  DIALECT_NAME
  fhelium_dist)

declare_mlir_dialect_python_bindings(
  ADD_TO_PARENT
  FHEliumPythonSources
  ROOT_DIR
  "${CMAKE_CURRENT_SOURCE_DIR}/package"
  TD_FILE
  dialects/MemoryOps.td
  SOURCES
  dialects/fhelium_memory.py
  DIALECT_NAME
  fhelium_memory)

declare_mlir_python_extension(
  FHEliumPythonSources.Extension
  MODULE_NAME
  _fhelium_compiler
  ADD_TO_PARENT
  FHEliumPythonSources
  SOURCES
  CompilerExtension.cpp
  PRIVATE_LINK_LIBS
  LLVMSupport
  EMBED_CAPI_LINK_LIBS
  MLIRCAPIIR
  MLIRCAPITransforms
  MLIRCAPIFunc
  MLIRCAPIArith
  FHEliumCAPICKKS
  FHEliumCAPILogical
  FHEliumCAPIDist
  FHEliumCAPIMemory
  FHEliumCAPITransforms
  FHEliumCAPIAnalysis)

# fhelium_ckks attribute and type constructors.
declare_mlir_python_extension(
  FHEliumPythonSources.CKKSTypesExtension
  MODULE_NAME
  _fhelium_ckks_types
  ADD_TO_PARENT
  FHEliumPythonSources
  SOURCES
  CKKSTypesExtension.cpp
  PRIVATE_LINK_LIBS
  LLVMSupport
  EMBED_CAPI_LINK_LIBS
  MLIRCAPIIR
  FHEliumCAPICKKS)

# RNS/NTT dialects, CKKS-to-RNS passes and link plans.
declare_mlir_python_extension(
  FHEliumPythonSources.BackendExtension
  MODULE_NAME
  _fhelium_backend
  ADD_TO_PARENT
  FHEliumPythonSources
  SOURCES
  BackendExtension.cpp
  PRIVATE_LINK_LIBS
  LLVMSupport
  EMBED_CAPI_LINK_LIBS
  MLIRCAPIIR
  FHEliumCAPIRNS
  FHEliumCAPINTT
  FHEliumCAPITransforms
  FHEliumCAPIAnalysis)

# exec dialect and Runner schedules.
declare_mlir_dialect_python_bindings(
  ADD_TO_PARENT
  FHEliumPythonSources
  ROOT_DIR
  "${CMAKE_CURRENT_SOURCE_DIR}/package"
  TD_FILE
  dialects/ExecOps.td
  SOURCES
  dialects/exec.py
  DIALECT_NAME
  exec)

declare_mlir_python_extension(
  FHEliumPythonSources.ScheduleExtension
  MODULE_NAME
  _fhelium_schedule
  ADD_TO_PARENT
  FHEliumPythonSources
  SOURCES
  ScheduleExtension.cpp
  PRIVATE_LINK_LIBS
  LLVMSupport
  EMBED_CAPI_LINK_LIBS
  MLIRCAPIIR
  MLIRCAPISCF
  FHEliumSchedule)
list(APPEND FHELIUM_PYTHON_STUB_MODULES _fhelium_schedule)

add_mlir_python_common_capi_library(
  FHEliumPythonCAPI
  INSTALL_COMPONENT
  FHEliumPythonModules
  INSTALL_DESTINATION
  "${MLIR_BINDINGS_PYTHON_INSTALL_PREFIX}/_mlir_libs"
  OUTPUT_DIRECTORY
  "${FHELIUM_MLIR_PYTHON_BUILD_ROOT}/_mlir_libs"
  RELATIVE_INSTALL_ROOT
  "../../../.."
  DECLARED_SOURCES
  FHEliumPythonSources
  MLIRPythonSources.Core
  MLIRPythonSources.Dialects.builtin
  MLIRPythonSources.Dialects.func
  MLIRPythonSources.Dialects.arith
  MLIRPythonSources.Dialects.scf)
# Extensions load the library by its unversioned file name; wheels cannot hold
# the versioned-name symbolic link.
set_property(TARGET FHEliumPythonCAPI PROPERTY VERSION)
set_property(TARGET FHEliumPythonCAPI PROPERTY SOVERSION)

# Type stubs of the extension modules, generated by nanobind's stubgen from the
# built modules. Further extensions append their module names to
# FHELIUM_PYTHON_STUB_MODULES before this block.
#
# The stub rule of MLIR 23 (mlir_generate_type_stubs in AddMLIRPython.cmake)
# removes the MLIR install prefix from PYTHONPATH with a regular expression
# built from the native path. On Windows, its trailing separator "\" escapes the
# closing parenthesis and the backslashes of the path become escapes, so
# configuration fails with "Unmatched ( or \(". fhelium_generate_type_stubs runs
# the same stubgen command with PYTHONPATH unset instead, on every platform, so
# that only the -i import paths of the build tree are imported.
set(FHELIUM_PYTHON_ROOT "${FHELIUM_MLIR_PYTHON_BUILD_ROOT}")
if(NOT DEFINED MLIR_PYTHON_STUBGEN_ENABLED)
  set(MLIR_PYTHON_STUBGEN_ENABLED ON)
endif()
list(APPEND FHELIUM_PYTHON_STUB_MODULES _fhelium_compiler _fhelium_ckks_types
     _fhelium_backend)

function(fhelium_generate_type_stubs)
  cmake_parse_arguments(ARG "" "MODULE_NAME;OUTPUT_DIR"
                        "IMPORT_PATHS;DEPENDS_TARGETS;OUTPUTS" ${ARGN})
  set(_import_paths)
  foreach(_import_path IN LISTS ARG_IMPORT_PATHS)
    file(REAL_PATH "${_import_path}" _import_path)
    list(APPEND _import_paths -i "${_import_path}")
  endforeach()
  list(TRANSFORM ARG_OUTPUTS PREPEND "${ARG_OUTPUT_DIR}/" OUTPUT_VARIABLE
                                                          _outputs)
  add_custom_command(
    OUTPUT ${_outputs}
    COMMAND
      ${CMAKE_COMMAND} -E env --unset=PYTHONPATH "${Python_EXECUTABLE}"
      "${CMAKE_CURRENT_BINARY_DIR}/stubgen.py" --module "${ARG_MODULE_NAME}"
      ${_import_paths} --recursive --include-private --output-dir
      "${ARG_OUTPUT_DIR}" --quiet
    DEPENDS ${ARG_DEPENDS_TARGETS} "${CMAKE_CURRENT_BINARY_DIR}/stubgen.py"
            ${FHELIUM_STUB_PYTHON_SOURCES}
    COMMENT "Generating type stubs of ${ARG_MODULE_NAME}")
  list(JOIN ARG_DEPENDS_TARGETS "." _name)
  set(_name "${_name}.${ARG_MODULE_NAME}.type_stubs")
  add_custom_target("${_name}" DEPENDS ${_outputs})
  set(FHELIUM_STUB_TARGET
      "${_name}"
      PARENT_SCOPE)
endfunction()

set(_fhelium_stub_targets)
if(MLIR_PYTHON_STUBGEN_ENABLED)
  foreach(_candidate "${nanobind_DIR}/../src/stubgen.py"
                     "${nanobind_DIR}/../stubgen.py")
    if(EXISTS "${_candidate}")
      file(REAL_PATH "${_candidate}" FHELIUM_NB_STUBGEN)
    endif()
  endforeach()
  if(NOT FHELIUM_NB_STUBGEN)
    message(
      FATAL_ERROR "nanobind's stubgen.py is not found next to ${nanobind_DIR}")
  endif()
  configure_file(stubgen.py.in "${CMAKE_CURRENT_BINARY_DIR}/stubgen.py" @ONLY)
  # stubgen names the MLIR types of the extension signatures, such as
  # fhelium._mlir.ir.Context, by the modules it can import from the build tree;
  # without the copied fhelium._mlir.ir it writes "import fhelium._mlir".
  set(FHELIUM_STUB_PYTHON_SOURCES
      "${FHELIUM_PYTHON_ROOT}/ir.py"
      "${FHELIUM_PYTHON_ROOT}/_mlir_libs/__init__.py")
  set(_core_stubs _mlir/__init__.pyi _mlir/ir.pyi _mlir/passmanager.pyi
                  _mlir/rewrite.pyi)
  fhelium_generate_type_stubs(
    MODULE_NAME
    _mlir
    DEPENDS_TARGETS
    FHEliumPythonModules.extension._mlir.dso
    OUTPUT_DIR
    "${CMAKE_CURRENT_BINARY_DIR}/type_stubs/_mlir_libs"
    OUTPUTS
    ${_core_stubs}
    IMPORT_PATHS
    "${FHELIUM_PYTHON_ROOT}/_mlir_libs")
  list(APPEND _fhelium_stub_targets "${FHELIUM_STUB_TARGET}")
  list(TRANSFORM _core_stubs PREPEND "_mlir_libs/")
  set(_fhelium_stub_sources ${_core_stubs})
  foreach(_module IN LISTS FHELIUM_PYTHON_STUB_MODULES)
    fhelium_generate_type_stubs(
      MODULE_NAME
      "${MLIR_PYTHON_PACKAGE_PREFIX}._mlir_libs.${_module}"
      DEPENDS_TARGETS
      FHEliumPythonModules.extension._mlir.dso
      FHEliumPythonModules.extension.${_module}.dso
      OUTPUT_DIR
      "${CMAKE_CURRENT_BINARY_DIR}/type_stubs/_mlir_libs"
      OUTPUTS
      "${_module}.pyi"
      IMPORT_PATHS
      "${FHELIUM_PYTHON_ROOT}/../..")
    list(APPEND _fhelium_stub_targets "${FHELIUM_STUB_TARGET}")
    list(APPEND _fhelium_stub_sources "_mlir_libs/${_module}.pyi")
  endforeach()
  declare_mlir_python_sources(
    FHEliumPythonSources.type_stubs
    ROOT_DIR
    "${CMAKE_CURRENT_BINARY_DIR}/type_stubs"
    ADD_TO_PARENT
    FHEliumPythonSources
    SOURCES
    ${_fhelium_stub_sources})
endif()

add_mlir_python_modules(
  FHEliumPythonModules
  ROOT_PREFIX
  "${FHELIUM_MLIR_PYTHON_BUILD_ROOT}"
  INSTALL_PREFIX
  "${MLIR_BINDINGS_PYTHON_INSTALL_PREFIX}"
  DECLARED_SOURCES
  FHEliumPythonSources
  MLIRPythonSources.Core
  MLIRPythonSources.Dialects.builtin
  MLIRPythonSources.Dialects.func
  MLIRPythonSources.Dialects.arith
  MLIRPythonSources.Dialects.scf
  COMMON_CAPI_LINK_LIBS
  FHEliumPythonCAPI)

foreach(_target IN LISTS _fhelium_stub_targets)
  add_dependencies(FHEliumPythonModules "${_target}")
endforeach()
