# FindFFmpeg.cmake
# Locates the prebuilt FFmpeg dev package in third_party/ffmpeg.
# Sets up IMPORTED targets: FFmpeg::avcodec  FFmpeg::avformat
#                           FFmpeg::avutil   FFmpeg::swscale
# and an umbrella: FFmpeg::FFmpeg

set(FFMPEG_ROOT "${CMAKE_SOURCE_DIR}/third_party/ffmpeg"
    CACHE PATH "FFmpeg install root (contains bin/ include/ lib/)")

set(FFmpeg_FOUND TRUE)

foreach(_comp avcodec avformat avutil swscale)
    # Import library (.lib) — required for MSVC linking
    find_library(FFmpeg_${_comp}_LIB
        NAMES ${_comp}
        PATHS "${FFMPEG_ROOT}/lib"
        NO_DEFAULT_PATH
    )

    # Runtime DLL — name includes a version suffix, e.g. avcodec-62.dll
    file(GLOB _dlls "${FFMPEG_ROOT}/bin/${_comp}-*.dll")
    if(_dlls)
        list(GET _dlls 0 FFmpeg_${_comp}_DLL)
    else()
        set(FFmpeg_${_comp}_DLL "")
    endif()

    if(NOT FFmpeg_${_comp}_LIB)
        set(FFmpeg_FOUND FALSE)
        message(STATUS "FFmpeg: ${_comp}.lib NOT found in ${FFMPEG_ROOT}/lib")
        continue()
    endif()
    if(NOT FFmpeg_${_comp}_DLL)
        set(FFmpeg_FOUND FALSE)
        message(STATUS "FFmpeg: ${_comp}-*.dll NOT found in ${FFMPEG_ROOT}/bin")
        continue()
    endif()

    add_library(FFmpeg::${_comp} SHARED IMPORTED)
    set_target_properties(FFmpeg::${_comp} PROPERTIES
        IMPORTED_IMPLIB              "${FFmpeg_${_comp}_LIB}"
        IMPORTED_LOCATION            "${FFmpeg_${_comp}_DLL}"
        INTERFACE_INCLUDE_DIRECTORIES "${FFMPEG_ROOT}/include"
    )
    message(STATUS "FFmpeg: ${_comp} -> ${FFmpeg_${_comp}_LIB}")
endforeach()

if(FFmpeg_FOUND)
    # Umbrella target so callers can just link FFmpeg::FFmpeg
    if(NOT TARGET FFmpeg::FFmpeg)
        add_library(FFmpeg::FFmpeg INTERFACE IMPORTED)
        set_target_properties(FFmpeg::FFmpeg PROPERTIES
            INTERFACE_LINK_LIBRARIES
                "FFmpeg::avcodec;FFmpeg::avformat;FFmpeg::avutil;FFmpeg::swscale"
            INTERFACE_INCLUDE_DIRECTORIES
                "${FFMPEG_ROOT}/include"
        )
    endif()
endif()

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(FFmpeg
    REQUIRED_VARS FFmpeg_avcodec_LIB FFmpeg_avformat_LIB
                  FFmpeg_avutil_LIB  FFmpeg_swscale_LIB)
