package com.phostt

/**
 * Kotlin JNI bridge for the phostt on-device Vietnamese STT engine.
 *
 * This object loads the native `libphostt.so` (built via cargo-ndk) and exposes
 * four externals that map 1:1 to the C-ABI functions in `src/ffi.rs`.
 *
 * Usage:
 * ```kotlin
 * val enginePtr = PhosttBridge.engineNew(modelDir)
 * if (enginePtr == 0L) throw RuntimeException("Failed to load engine")
 * try {
 *     val text = PhosttBridge.transcribeFile(enginePtr, wavPath)
 *     println("Transcription: $text")
 * } finally {
 *     PhosttBridge.engineFree(enginePtr)
 * }
 * ```
 */
object PhosttBridge {
    init {
        System.loadLibrary("phostt")
    }

    /**
     * Load the ONNX models from [modelDir] and create an inference engine.
     *
     * @param modelDir Absolute path to the directory containing
     *                 `encoder.int8.onnx`, `decoder.onnx`, `joiner.int8.onnx`,
     *                 `bpe.model`, and `tokens.txt`.
     * @return An opaque native pointer (cast to `Long`), or `0L` on failure.
     */
    @JvmStatic
    external fun engineNew(modelDir: String): Long

    /**
     * Transcribe a WAV (or MP3/FLAC/OGG/M4A) file to text.
     *
     * @param enginePtr Pointer returned by [engineNew].
     * @param wavPath Absolute path to the audio file.
     * @return The recognized text, or an empty string on failure.
     */
    @JvmStatic
    external fun transcribeFile(enginePtr: Long, wavPath: String): String

    /**
     * Free a string previously returned by [transcribeFile].
     *
     * **Note:** The Kotlin JNI glue generated by `javah` / `javac -h` normally
     * copies the `jstring` into a JVM-managed `String` object, so the C string
     * returned by Rust is immediately eligible for freeing.  If you change the
     * JNI layer to keep the raw C pointer alive (e.g. zero-copy), you must call
     * this method explicitly.
     *
     * @param ptr Raw C string pointer (as `Long`).
     */
    @JvmStatic
    external fun stringFree(ptr: Long)

    /**
     * Tear down the inference engine and release all ONNX sessions.
     *
     * @param enginePtr Pointer returned by [engineNew].
     */
    @JvmStatic
    external fun engineFree(ptr: Long)
}
