# Copyright Contributors to the OpenImageIO project.
# SPDX-License-Identifier: Apache-2.0
# https://github.com/AcademySoftwareFoundation/OpenImageIO


# Setup the pystubs target, which is not built by default.

# The stubs are generated by nanobind's stubgen, using the pattern file below
# to apply the signature overrides the stubs have always carried (formerly done
# by mypy's stubgen plus the hand-maintained overrides in generate_stubs.py,
# see #5489). Unlike the old recipe there is no need to build a wheel in a
# container: the generator imports the freshly built extension module directly
# from the build tree. Stubs are only generated for the nanobind bindings
# backend; for a pybind11 build the pystubs target is not available.

set (_stub_file "${CMAKE_SOURCE_DIR}/src/python/stubs/OpenImageIO/__init__.pyi")
set (_pattern_file "${CMAKE_SOURCE_DIR}/src/python/stubs/OpenImageIO_patterns.pyi")

if (NOT nanobind_DIR OR NOT EXISTS "${nanobind_DIR}/../stubgen.py")
    message (STATUS "pystubs target disabled: nanobind not found "
                    "(stubs are only generated for the nanobind backend)")
    return ()
endif ()

# The stub generator imports the freshly built OpenImageIO extension module,
# so give it the build-tree directory of the OpenImageIO library, in case the
# module links against a shared build of it.
set (_stubgen_libpath "")
if (TARGET OpenImageIO)
    set (_stubgen_libpath "$<TARGET_FILE_DIR:OpenImageIO>")
endif ()

add_custom_command (
        COMMAND ${CMAKE_COMMAND} -E make_directory
                    "${CMAKE_BINARY_DIR}/stubs/OpenImageIO"
        COMMAND ${CMAKE_COMMAND} -E env
                    "LD_LIBRARY_PATH=${_stubgen_libpath}"
                    "DYLD_LIBRARY_PATH=${_stubgen_libpath}"
                    ${Python3_EXECUTABLE} "${nanobind_DIR}/../stubgen.py"
                        -i "$<TARGET_PROPERTY:PyOpenImageIO,LIBRARY_OUTPUT_DIRECTORY>"
                        -p "${_pattern_file}"
                        -m OpenImageIO
                        -o "${CMAKE_BINARY_DIR}/stubs/OpenImageIO/__init__.pyi"
        OUTPUT "${CMAKE_BINARY_DIR}/stubs/OpenImageIO/__init__.pyi"
        DEPENDS PyOpenImageIO "${_pattern_file}"
        COMMENT "pystubs: generating python stubs with nanobind stubgen"
        VERBATIM)

add_custom_command (
        COMMAND ${Python3_EXECUTABLE} -c "import pathlib; src = pathlib.Path('${CMAKE_BINARY_DIR}/stubs/OpenImageIO/__init__.pyi'); dst = pathlib.Path('${_stub_file}'); dst.write_text('#\\n# This file is auto-generated. DO NOT MODIFY!  Run \`make pystubs\` to regenerate\\n#\\n\\n' + src.read_text())"
        OUTPUT ${_stub_file}
        DEPENDS "${CMAKE_BINARY_DIR}/stubs/OpenImageIO/__init__.pyi"
        COMMENT "pystubs: Copying generated stubs to source"
        VERBATIM)

add_custom_target (pystubs DEPENDS ${_stub_file})
