cmake_minimum_required(VERSION 3.5.1)

# Set compiler based on platform (must be done before project() call)
if(WIN32)
    # Force clang-cl on Windows for all targets
    set(CMAKE_CXX_COMPILER "clang-cl" CACHE STRING "C++ compiler" FORCE)
    set(CMAKE_C_COMPILER "clang-cl" CACHE STRING "C compiler" FORCE)
endif()

# Set C++17 standard for all platforms
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

project(dldt)

if(NOT DEFINED ENV{DLICC_PATH})
    message(FATAL_ERROR "Sdk env is invalid!, build process will stop. source sdk/env.sh please!")
endif()

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Get SDK path for installation
get_filename_component(SDK_PATH "$ENV{DLICC_PATH}/../" ABSOLUTE)

# Set install prefix to SDK root by default
# If user hasn't explicitly set CMAKE_INSTALL_PREFIX (i.e., it's still the default),
# use SDK path. This works for both Linux (/usr/local) and Windows defaults.
if(CMAKE_INSTALL_PREFIX STREQUAL "/usr/local" OR
   CMAKE_INSTALL_PREFIX STREQUAL "/usr/local/" OR
   CMAKE_INSTALL_PREFIX MATCHES "C:/Program Files")
    set(CMAKE_INSTALL_PREFIX "${SDK_PATH}" CACHE PATH "Install path prefix" FORCE)
    message(STATUS "Setting install prefix to SDK: ${SDK_PATH}")
else()
    message(STATUS "Using custom install prefix: ${CMAKE_INSTALL_PREFIX}")
endif()

if(DEFINED ENV{DLI_V2})
    set(DLI_V2 $ENV{DLI_V2})
    message(STATUS "Chip arch is DLI_V2")
    add_definitions(-DDLI_V2)
else()
    set(DLI_V1 "DLI_V1")
    message(STATUS "Chip arch is DLI_V1")
    add_definitions(-DDLI_V1)
endif()

add_definitions(-DPROJECT_SOURCE_DIR="${CMAKE_SOURCE_DIR}")

# Windows-specific settings
if(WIN32)
    add_compile_options(/wd4996)  # Disable CRT security warnings (fopen, getenv, etc.)
    add_compile_options(/DNOMINMAX)  # Prevent min/max macro conflicts
endif()

message(STATUS "CMAKE_INSTALL_PREFIX: ${CMAKE_INSTALL_PREFIX}")

# Define install directories with dldt subdirectory
if(NOT DEFINED CMAKE_INSTALL_INCLUDEDIR)
    set(CMAKE_INSTALL_INCLUDEDIR include/dldt)
endif()

if(NOT DEFINED CMAKE_INSTALL_LIBDIR)
    set(CMAKE_INSTALL_LIBDIR lib)
endif()

if(NOT DEFINED CMAKE_INSTALL_PYTHONDIR)
    set(CMAKE_INSTALL_PYTHONDIR python/dldt)
endif()

message(STATUS "Install directories:")
message(STATUS "  Headers: ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}")
message(STATUS "  Libraries: ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}")
message(STATUS "  Python: ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_PYTHONDIR}")

# Option to build CUDA kernel library (default ON for backward compatibility)
option(BUILD_CUDA_KERNEL "Build CUDA kernel library" ON)

# Option to build DLDT libraries (default ON)
option(BUILD_DLDT "Build DLDT libraries" ON)

# Option to build Python bindings (pydldt)
option(BUILD_PYDLDT "Build Python bindings (pydldt)" OFF)

# Option to build video codec modules (default ON)
option(BUILD_VIDEO "Build video codec modules" ON)

# Option to build JPEG codec modules (default ON)
option(BUILD_JPEG "Build JPEG codec modules" ON)

# Option to build network modules (default ON)
option(BUILD_NETWORK "Build network modules" ON)

# Option to build tests (default OFF for backward compatibility)
option(BUILD_TESTS "Build tests" OFF)

# Custom FFmpeg path (optional)
if(DEFINED FFMPEG_ROOT AND NOT FFMPEG_ROOT STREQUAL "")
    message(STATUS "Using custom FFmpeg path: ${FFMPEG_ROOT}")
    # Add custom FFmpeg include and lib paths
    list(APPEND CMAKE_PREFIX_PATH "${FFMPEG_ROOT}")
    include_directories(${FFMPEG_ROOT}/include)
    link_directories(${FFMPEG_ROOT}/lib)
    # Set pkg-config path for custom FFmpeg
    set(ENV{PKG_CONFIG_PATH} "${FFMPEG_ROOT}/lib/pkgconfig:$ENV{PKG_CONFIG_PATH}")
    # Add rpath-link for finding FFmpeg dependencies at link time.
    # -Wl,-rpath-link is a GNU/ELF linker option; on Windows (lld-link) it is
    # unknown and, when FFMPEG_ROOT contains a space, the unquoted flag is
    # split into a bogus file argument that breaks linking. Skip it on Windows.
    if(NOT WIN32)
        link_libraries("-Wl,-rpath-link,${FFMPEG_ROOT}/lib")
    endif()
endif()

# # Default log level for compilation (0=OFF, 1=FATAL, 2=ERROR, 3=WARN, 4=INFO, 5=DEBUG, 6=TRACE)
# if(NOT DEFINED DLDT_LOG_LEVEL)
#     set(DLDT_LOG_LEVEL 6 CACHE STRING "DLDT compile-time log level (0=OFF, 1=FATAL, 2=ERROR, 3=WARN, 4=INFO, 5=DEBUG, 6=TRACE)")
# endif()
# add_compile_options(-DDLDT_LOG_LEVEL=${DLDT_LOG_LEVEL})

if(BUILD_CUDA_KERNEL)
    add_subdirectory(dldt_cuda_kernel)
endif()

# dldt modules (jpeg, video, network as shared libraries)
if(BUILD_DLDT)
    add_subdirectory(dldt)
endif()

# Optional: Python bindings
if(BUILD_PYDLDT)
    add_subdirectory(pydldt)
endif()

if(BUILD_TESTS)
    add_subdirectory(tests)
endif()

# Copy samples to build directory for development/testing
add_custom_target(copy_samples ALL
    COMMAND ${CMAKE_COMMAND} -E copy_directory
        ${CMAKE_SOURCE_DIR}/samples
        ${CMAKE_CURRENT_BINARY_DIR}/samples
    COMMENT "Copying samples to build directory"
)

# Print installation summary
message(STATUS "")
message(STATUS "=================================")
message(STATUS "DLDT Configuration Summary")
message(STATUS "=================================")
message(STATUS "SDK Path:            ${SDK_PATH}")
message(STATUS "Install Prefix:      ${CMAKE_INSTALL_PREFIX}")
message(STATUS "  Headers:           ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}")
message(STATUS "  Libraries:         ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}")
message(STATUS "  Python:            ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_PYTHONDIR}")
message(STATUS "Compile-time Log Level: ${DLDT_LOG_LEVEL} (0=OFF, 1=FATAL, 2=ERROR, 3=WARN, 4=INFO, 5=DEBUG, 6=TRACE)")
message(STATUS "")
message(STATUS "Build Options:")
message(STATUS "  DLDT:              ${BUILD_DLDT}")
message(STATUS "  PYDLDT:            ${BUILD_PYDLDT}")
message(STATUS "  CUDA Kernel:       ${BUILD_CUDA_KERNEL}")
message(STATUS "  JPEG Codec:        ${BUILD_JPEG}")
message(STATUS "  Video Codec:       ${BUILD_VIDEO}")
message(STATUS "  Network:           ${BUILD_NETWORK}")
message(STATUS "  Tests:             ${BUILD_TESTS}")
if(DEFINED FFMPEG_ROOT AND NOT FFMPEG_ROOT STREQUAL "")
    message(STATUS "  Custom FFmpeg:     ${FFMPEG_ROOT}")
endif()
message(STATUS "=================================")
message(STATUS "")
message(STATUS "After build, run 'make install' to install DLDT to SDK")
message(STATUS "")

# Uninstall target: remove installed dldt files from SDK
add_custom_target(uninstall
    COMMAND ${CMAKE_COMMAND} -E echo "Uninstalling dldt from ${CMAKE_INSTALL_PREFIX} ..."
    COMMAND ${CMAKE_COMMAND} -E remove_directory ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}
    COMMAND ${CMAKE_COMMAND} -E remove -f ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/libdldt_*.so
    COMMAND ${CMAKE_COMMAND} -E remove -f ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/libdldt_cuda_kernel.so
    COMMAND ${CMAKE_COMMAND} -E remove_directory ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_PYTHONDIR}
    COMMAND ${CMAKE_COMMAND} -E echo "Done."
)
