# Resolves pre-built SDL3 libraries based on PLATFORM and SDL_LINK_TYPE.
#
# Windows: prebuilt/windows/ is committed to the repository.
#          Run scripts/bootstrap_sdl_windows.ps1 once to (re)generate it.
# Linux:   prebuilt/linux/ is built in-place on the Linux remote.
#          Run scripts/bootstrap_sdl_linux.sh once after cloning.

set(SDL_PREBUILT_DIR "${CMAKE_SOURCE_DIR}/prebuilt/${PLATFORM}")

if(SDL_LINK_TYPE STREQUAL "static")
    set(SDL_SEARCH_DIR "${SDL_PREBUILT_DIR}/SDL3-static")
else()
    set(SDL_SEARCH_DIR "${SDL_PREBUILT_DIR}/SDL3-dynamic")
endif()

message(STATUS "Looking for SDL3 in: ${SDL_SEARCH_DIR}")

find_package(SDL3 REQUIRED CONFIG
    PATHS "${SDL_SEARCH_DIR}"
    NO_DEFAULT_PATH
)

if(SDL_LINK_TYPE STREQUAL "static")
    set(SDL_TARGET SDL3::SDL3-static)
else()
    set(SDL_TARGET SDL3::SDL3)
endif()

message(STATUS "SDL_TARGET resolved to: ${SDL_TARGET}")

# On Windows with dynamic linking, copy the DLL next to the executable
if(SDL_LINK_TYPE STREQUAL "dynamic" AND WIN32)
    add_custom_target(copy_sdl_dll ALL
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
            $<TARGET_FILE:SDL3::SDL3>
            "${CMAKE_BINARY_DIR}/game/$<TARGET_FILE_NAME:SDL3::SDL3>"
        COMMENT "Copying SDL3.dll to output directory"
    )
endif()

# On Linux with dynamic linking, embed the absolute path to the prebuilt lib
# directory in the binary's RPATH. prebuilt/linux is built in-place on the
# Linux remote so this path is always valid there.
if(SDL_LINK_TYPE STREQUAL "dynamic" AND UNIX AND NOT APPLE)
    get_target_property(SDL3_SO_LOCATION SDL3::SDL3 LOCATION)
    get_filename_component(SDL3_LIB_DIR "${SDL3_SO_LOCATION}" DIRECTORY)
    message(STATUS "SDL3 runtime library directory: ${SDL3_LIB_DIR}")
    set(SDL_LINUX_RPATH "${SDL3_LIB_DIR}" CACHE INTERNAL "")
endif()