#
# Project NuriKit - Copyright 2024 SNU Compbio Lab.
# SPDX-License-Identifier: Apache-2.0
#

if(NURI_BUILD_PYTHON_STUBS)
  find_program(PYBIND11_STUBGEN pybind11-stubgen)
  mark_as_advanced(PYBIND11_STUBGEN)

  if(PYBIND11_STUBGEN)
    message(NOTICE "Generating Python stubs for NuriKit")
  else()
    message(WARNING "pybind11-stubgen not found, cannot generate stubs")
    set(NURI_BUILD_PYTHON_STUBS OFF)
  endif()
endif()

add_custom_target(NuriPython ALL)
clear_coverage_data(NuriPython)

if(NURI_BUILD_LIB)
  add_dependencies(NuriPython NuriLib)
endif()

include(NuriKitPythonUtils)

file(
  GLOB_RECURSE NURI_PYTHON_FILES
  RELATIVE "${CMAKE_CURRENT_LIST_DIR}/"
  CONFIGURE_DEPENDS
  "nuri/*.py" "nuri/py.typed"
)
list(FILTER NURI_PYTHON_FILES EXCLUDE REGEX "^nuri/_version\\.py$")

file(GLOB_RECURSE staged_pyfiles "${NURI_PYTHON_STAGE_DIR}/nuri/*.py")

if(staged_pyfiles)
  file(REMOVE ${staged_pyfiles})
endif()

foreach(pyfile IN LISTS NURI_PYTHON_FILES)
  get_filename_component(pydir "${pyfile}" DIRECTORY)
  file(MAKE_DIRECTORY "${NURI_PYTHON_STAGE_DIR}/${pydir}")
  file(CREATE_LINK
    "${CMAKE_CURRENT_LIST_DIR}/${pyfile}"
    "${NURI_PYTHON_STAGE_DIR}/${pyfile}"
    SYMBOLIC
  )
endforeach()

configure_file(
  "${CMAKE_CURRENT_LIST_DIR}/nuri/_version.py.in"
  "${NURI_PYTHON_STAGE_DIR}/nuri/_version.py"
  @ONLY
)

nuri_python_add_module(log_interface OUTPUT_DIRECTORY "_support"
  nuri/_support/log_interface_module.cpp
)
target_link_libraries("${NURI_PYTHON_MODULE_TARGET}"
  PRIVATE absl::log_initialize
)

nuri_python_add_module(core
  nuri/core/core_module.cpp
  nuri/core/containers.cpp
  nuri/core/element.cpp
  nuri/core/molecule.cpp
  nuri/core/substructure.cpp
  nuri/core/geometry.cpp
  OUTPUT_STUBS nuri/core/__init__.pyi nuri/core/geometry.pyi
)

nuri_python_add_module(algo
  nuri/algo/algo_module.cpp
)

nuri_python_add_module(desc
  nuri/desc/desc_module.cpp
)

nuri_python_add_module(param
  nuri/param/param_module.cpp
)

nuri_python_add_module(fmt
  nuri/fmt/fmt_module.cpp
  nuri/fmt/cif.cpp
  nuri/fmt/pdb.cpp
  OUTPUT_STUBS nuri/fmt/__init__.pyi nuri/fmt/cif.pyi nuri/fmt/pdb.pyi
)
target_link_libraries("${NURI_PYTHON_MODULE_TARGET}"
  PRIVATE absl::span absl::synchronization
)

nuri_python_add_module(tm OUTPUT_DIRECTORY "tools"
  nuri/tools/tm_module.cpp
)

nuri_python_add_module(galign OUTPUT_DIRECTORY "tools"
  nuri/tools/galign_module.cpp
)

nuri_python_add_module(chimera OUTPUT_DIRECTORY "tools"
  nuri/tools/chimera_module.cpp
)

if(SKBUILD)
  install(
    FILES "${NURI_PYTHON_STAGE_DIR}/nuri/_version.py"
    DESTINATION "."
  )
endif()

if(NURI_BUILD_PYTHON_STUBS)
  add_custom_target(NuriPythonStubs
    ALL
    DEPENDS NuriPython ${NURI_STUB_FILES}
  )
  clear_coverage_data(NuriPythonStubs)
endif()
