cmake_minimum_required(VERSION 3.18)
project(doc2struct LANGUAGES C)
option(DOC2STRUCT_BUILD_PYTHON "Build the Python extension" OFF)
add_subdirectory(c)

if(DOC2STRUCT_BUILD_PYTHON)
    find_package(Python REQUIRED COMPONENTS Interpreter Development.Module)
    Python_add_library(_native MODULE WITH_SOABI python/native/module.c)
    target_link_libraries(_native PRIVATE doc2struct::doc2struct)
    set_target_properties(_native PROPERTIES C_STANDARD 11 C_STANDARD_REQUIRED YES)
    if(MSVC)
        target_compile_options(_native PRIVATE /utf-8)
    endif()
    get_filename_component(PDFIUM_DIRECTORY "${PDFIUM_LIBRARY}" DIRECTORY)
    set(PDFIUM_METADATA "${PDFIUM_DIRECTORY}/version.json")
    execute_process(COMMAND "${Python_EXECUTABLE}"
        "${CMAKE_CURRENT_SOURCE_DIR}/build_scripts/validate_pdfium.py"
        "${PDFIUM_LIBRARY}" --licenses "${PDFIUM_LICENSE_DIR}" RESULT_VARIABLE PDFIUM_VALIDATION)
    if(NOT PDFIUM_VALIDATION EQUAL 0)
        message(FATAL_ERROR "PDFium runtime validation failed")
    endif()
    install(TARGETS _native LIBRARY DESTINATION doc2struct COMPONENT python RUNTIME DESTINATION doc2struct COMPONENT python)
    install(FILES "${PDFIUM_LIBRARY}" DESTINATION doc2struct/_pdfium RENAME "doc2struct_pdfium${CMAKE_SHARED_LIBRARY_SUFFIX}" COMPONENT python)
    install(FILES "${PDFIUM_METADATA}" DESTINATION doc2struct/_pdfium COMPONENT python)
    install(DIRECTORY "${PDFIUM_LICENSE_DIR}/" DESTINATION doc2struct/_pdfium/licenses COMPONENT python)
endif()
