# MeetRec whisper JNI — builds whisper.cpp (CPU backend) for Android.
#
# Mirrors the approach of whisper.cpp's own Android example: compile
# src/whisper.cpp directly and build ggml via FetchContent, instead of
# add_subdirectory-ing the full whisper.cpp CMake tree.

cmake_minimum_required(VERSION 3.22)
project(meetrec_whisper LANGUAGES C CXX)

set(CMAKE_CXX_STANDARD 17)

set(WHISPER_CPP "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../third_party/whisper.cpp")
if(NOT EXISTS "${WHISPER_CPP}/src/whisper.cpp")
    message(FATAL_ERROR
        "whisper.cpp sources not found at ${WHISPER_CPP}. "
        "Run ./tools/fetch-whisper.sh from the android/ directory first.")
endif()

set(SOURCE_FILES
    ${WHISPER_CPP}/src/whisper.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/whisper_jni.cpp)

find_library(LOG_LIB log)

include(FetchContent)
FetchContent_Declare(ggml SOURCE_DIR ${WHISPER_CPP}/ggml)
FetchContent_MakeAvailable(ggml)

add_library(whisper_jni SHARED ${SOURCE_FILES})

# whisper.cpp's src/whisper.cpp returns WHISPER_VERSION from
# whisper_print_system_info(); its own CMake normally defines it.
file(READ "${WHISPER_CPP}/CMakeLists.txt" _WC_MAIN)
if(_WC_MAIN MATCHES
        "set\\(WHISPER_VERSION_MAJOR ([0-9]+)\\).*\nset\\(WHISPER_VERSION_MINOR ([0-9]+)\\).*\nset\\(WHISPER_VERSION_PATCH ([0-9]+)\\)")
    set(WHISPER_VERSION "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3}")
else()
    set(WHISPER_VERSION "unknown")
endif()
message(STATUS "whisper.cpp version: ${WHISPER_VERSION}")
target_compile_definitions(whisper_jni PRIVATE WHISPER_VERSION="${WHISPER_VERSION}")

# CPU (NEON) backend only for now; GPU/QNN acceleration is a stretch goal.
target_compile_definitions(whisper_jni PUBLIC GGML_USE_CPU)

if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
    target_compile_options(whisper_jni PRIVATE -O3 -fvisibility=hidden)
    target_link_options(whisper_jni PRIVATE
        -Wl,--gc-sections -Wl,--exclude-libs,ALL -flto)
endif()

target_include_directories(whisper_jni PRIVATE
    ${WHISPER_CPP}/include
    ${WHISPER_CPP}/src
    ${WHISPER_CPP}/ggml/include)

target_link_libraries(whisper_jni PRIVATE ${LOG_LIB} android ggml)