//! FFI string utilities
//!
//! Helper functions for retrieving strings from C/Objective-C APIs
//! that use buffer-based string retrieval patterns.

use std::ffi::CStr;

/// Default buffer size for FFI string retrieval
pub const DEFAULT_BUFFER_SIZE: usize = 1024;

/// Smaller buffer size for short strings (e.g., device IDs, stream names)
pub const SMALL_BUFFER_SIZE: usize = 256;

/// Stack-allocate up to this many bytes — anything bigger falls back to a
/// heap `Vec`. 256 bytes covers every real call site (`SMALL_BUFFER_SIZE`,
/// audio device IDs, stream names, microphone IDs); the 1 KiB callers are
/// rare and currently absent from the codebase, so the heap fallback path
/// is essentially dead code today but kept for forward-compat with
/// future longer-string APIs.
const STACK_BUFFER_BYTES: usize = 256;

/// Retrieves a string from an FFI function that writes to a buffer.
///
/// This is a common pattern in Objective-C FFI where a function:
/// 1. Takes a buffer pointer and length
/// 2. Writes a null-terminated string to the buffer
/// 3. Returns a boolean indicating success
///
/// # Arguments
/// * `buffer_size` - Size of the buffer to allocate
/// * `ffi_call` - A closure that takes (`buffer_ptr`, `buffer_len`) and returns success bool
///
/// # Returns
/// * `Some(String)` if the FFI call succeeded and the string was valid UTF-8
/// * `None` if the FFI call failed or returned an empty string
///
/// # Safety
/// The caller must ensure the `ffi_call` closure does not write beyond the
/// provided `buffer_len`. This function defends against the closure writing
/// a non-NUL-terminated string by scanning the buffer up to its declared
/// length and treating the absence of a terminator as failure (returns
/// `None`) rather than reading past the buffer with `CStr::from_ptr`.
///
/// # Example
/// ```
/// use doom_fish_utils::ffi_string::ffi_string_from_buffer;
///
/// let result = unsafe {
///     ffi_string_from_buffer(64, |buf, len| {
///         // Simulate FFI call that writes "hello" to buffer
///         let src = b"hello\0";
///         if len >= src.len() as isize {
///             std::ptr::copy_nonoverlapping(src.as_ptr(), buf as *mut u8, src.len());
///             true
///         } else {
///             false
///         }
///     })
/// };
/// assert_eq!(result, Some("hello".to_string()));
/// ```
#[allow(clippy::cast_possible_wrap)]
pub unsafe fn ffi_string_from_buffer<F>(buffer_size: usize, ffi_call: F) -> Option<String>
where
    F: FnOnce(*mut i8, isize) -> bool,
{
    // Fast path: the typical small-getter case (audio device IDs, stream
    // names, microphone IDs) fits comfortably in 256 bytes and is called
    // often enough that the per-call `vec![0i8; 256]` heap allocation
    // adds up. Use a stack buffer for those and only fall back to a Vec
    // for unusually-large requests.
    if buffer_size <= STACK_BUFFER_BYTES {
        let mut buffer = [0i8; STACK_BUFFER_BYTES];
        let success = ffi_call(buffer.as_mut_ptr(), buffer_size as isize);
        if !success {
            return None;
        }
        return parse_buffer(&buffer[..buffer_size]);
    }

    let mut buffer = vec![0i8; buffer_size];
    let success = ffi_call(buffer.as_mut_ptr(), buffer.len() as isize);
    if !success {
        return None;
    }
    parse_buffer(&buffer)
}

/// Scan for the NUL terminator and decode the string portion.
/// Defensive: do NOT use `CStr::from_ptr` here. If the FFI closure
/// returned `true` but failed to write a NUL terminator, `CStr::from_ptr`
/// would read past the buffer until it found a zero byte — UB and a
/// potential information leak. Instead, scan only the buffer we
/// allocated and treat a missing terminator as failure.
fn parse_buffer(buffer: &[i8]) -> Option<String> {
    // SAFETY: `i8` and `u8` have identical layout; the cast is purely a
    // signed/unsigned reinterpretation.
    let bytes = unsafe { std::slice::from_raw_parts(buffer.as_ptr().cast::<u8>(), buffer.len()) };
    let nul_pos = bytes.iter().position(|&b| b == 0)?;
    let s = String::from_utf8_lossy(&bytes[..nul_pos]).into_owned();
    if s.is_empty() {
        None
    } else {
        Some(s)
    }
}

/// Same as [`ffi_string_from_buffer`] but returns an empty string on failure
/// instead of `None`.
///
/// Useful when the API should always return a string, even if empty.
///
/// # Safety
/// The caller must ensure that the FFI call writes valid UTF-8 data to the buffer.
#[allow(clippy::cast_possible_wrap)]
pub unsafe fn ffi_string_from_buffer_or_empty<F>(buffer_size: usize, ffi_call: F) -> String
where
    F: FnOnce(*mut i8, isize) -> bool,
{
    ffi_string_from_buffer(buffer_size, ffi_call).unwrap_or_default()
}

/// Retrieves a string from an FFI function that returns an owned C string pointer.
///
/// This is more efficient than buffer-based retrieval as it avoids pre-allocation.
/// The FFI function allocates the string (typically via Swift's `strdup`) and
/// this helper takes ownership and frees it using the caller-supplied
/// `free_fn`.
///
/// # Arguments
/// * `ffi_call` - A closure that returns an owned C string pointer (or null)
/// * `free_fn`  - A function that frees the pointer returned by `ffi_call`.
///   Each bridging crate passes its own `_free_string` `extern "C"` here
///   (e.g. `apple_cf::ffi::acf_free_string`,
///   `screencapturekit::ffi::sc_free_string`).
///
/// # Returns
/// * `Some(String)` if the pointer was non-null and the string was non-empty
/// * `None` if the pointer was null or the string was empty
///
/// # Safety
/// The caller must ensure the returned pointer was allocated by the Swift /
/// Objective-C side using a strategy that `free_fn` correctly releases.
/// The pointer is freed via an RAII guard, so a panic in `from_utf8_lossy`
/// (extremely rare — only OOM) does not leak the bridge-allocated buffer.
pub unsafe fn ffi_string_owned<F, Free>(ffi_call: F, free_fn: Free) -> Option<String>
where
    F: FnOnce() -> *mut i8,
    Free: FnOnce(*mut i8),
{
    /// RAII guard: releases the bridge-allocated buffer on drop, including
    /// during panic unwind. Without this, a panic between `CStr::from_ptr`
    /// and the explicit free call (e.g. allocator failure inside
    /// `from_utf8_lossy`) would leak the buffer.
    struct FreeGuard<F: FnOnce(*mut i8)> {
        ptr: *mut i8,
        free_fn: Option<F>,
    }
    impl<F: FnOnce(*mut i8)> Drop for FreeGuard<F> {
        fn drop(&mut self) {
            if !self.ptr.is_null() {
                if let Some(free) = self.free_fn.take() {
                    free(self.ptr);
                }
            }
        }
    }

    let ptr = ffi_call();
    if ptr.is_null() {
        return None;
    }
    let _guard = FreeGuard {
        ptr,
        free_fn: Some(free_fn),
    };
    // `to_string_lossy().to_string()` allocates twice on the valid-UTF-8
    // path: once for the borrowed Cow, then again for the explicit
    // `to_string`. `from_utf8_lossy(...).into_owned()` allocates once
    // and skips the redundant copy. For invalid UTF-8 (extremely rare
    // for AppKit strings) both paths allocate the replacement-char string.
    let bytes = CStr::from_ptr(ptr).to_bytes();
    if bytes.is_empty() {
        return None;
    }
    Some(String::from_utf8_lossy(bytes).into_owned())
}

/// Same as [`ffi_string_owned`] but returns an empty string on failure.
///
/// # Safety
/// Same requirements as [`ffi_string_owned`].
pub unsafe fn ffi_string_owned_or_empty<F, Free>(ffi_call: F, free_fn: Free) -> String
where
    F: FnOnce() -> *mut i8,
    Free: FnOnce(*mut i8),
{
    ffi_string_owned(ffi_call, free_fn).unwrap_or_default()
}

/// Take ownership of an already-obtained Swift/Objective-C C string pointer
/// and free the source via `free_fn`.
///
/// This matches the common `take_string(ptr) -> Option<String>` pattern that
/// every doom-fish crate has been duplicating locally. Use this from your
/// crate's bridge helper so the body lives in one place.
///
/// Returns `Some(String)` for a non-null, non-empty pointer; `None` otherwise.
/// In both branches the pointer is freed (the null branch is a no-op).
///
/// # Safety
///
/// The caller must guarantee that `ptr` is either null or a valid,
/// null-terminated C string allocated by the Swift / Objective-C bridge in a
/// way that `free_fn` correctly releases. The pointer is consumed exactly once.
#[inline]
pub unsafe fn take_owned_cstring<Free>(ptr: *mut i8, free_fn: Free) -> Option<String>
where
    Free: FnOnce(*mut i8),
{
    if ptr.is_null() {
        return None;
    }
    ffi_string_owned(|| ptr, free_fn)
}

/// Same as [`take_owned_cstring`] but for `*mut std::ffi::c_char`.
///
/// Rust 1.71+ distinguishes `c_char` from `i8` on some targets. Functionally
/// identical to the `i8` variant.
///
/// # Safety
///
/// Same requirements as [`take_owned_cstring`].
#[inline]
pub unsafe fn take_owned_cstring_c<Free>(
    ptr: *mut core::ffi::c_char,
    free_fn: Free,
) -> Option<String>
where
    Free: FnOnce(*mut core::ffi::c_char),
{
    if ptr.is_null() {
        return None;
    }
    let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
    free_fn(ptr);
    if bytes.is_empty() {
        None
    } else {
        Some(String::from_utf8_lossy(&bytes).into_owned())
    }
}

#[cfg(test)]
mod take_owned_tests {
    use super::*;
    use std::ffi::CString;

    #[test]
    fn take_owned_cstring_null_returns_none() {
        let freed = std::cell::Cell::new(false);
        let result = unsafe { take_owned_cstring(core::ptr::null_mut(), |_| freed.set(true)) };
        assert_eq!(result, None);
        assert!(!freed.get(), "free fn must not be called for null ptr");
    }

    #[test]
    fn take_owned_cstring_returns_value_and_frees() {
        let s = CString::new("hello").unwrap();
        let raw = s.into_raw();
        let freed = std::cell::Cell::new(false);
        let result = unsafe {
            take_owned_cstring(raw.cast::<i8>(), |p| {
                freed.set(true);
                let _ = CString::from_raw(p.cast::<core::ffi::c_char>());
            })
        };
        assert_eq!(result.as_deref(), Some("hello"));
        assert!(freed.get(), "free fn must be called for non-null ptr");
    }

    #[test]
    fn take_owned_cstring_c_returns_value_and_frees() {
        let s = CString::new("world").unwrap();
        let raw = s.into_raw();
        let freed = std::cell::Cell::new(false);
        let result = unsafe {
            take_owned_cstring_c(raw, |p| {
                freed.set(true);
                let _ = CString::from_raw(p);
            })
        };
        assert_eq!(result.as_deref(), Some("world"));
        assert!(freed.get());
    }
}
