// Auto-generated by alef — DO NOT EDIT

package {{ package }};

import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

/**
 * Service wrapper for {{ service_name }} using Panama FFM.
 *
 * Binds to C FFI symbols:
 * - {{ ffi_prefix }}_{{ service_snake }}_new() -> opaque handle
 * - {{ ffi_prefix }}_{{ service_snake }}_free(opaque)
{{ bindings_doc }} */
@SuppressWarnings("PMD")
public class {{ class_name }} implements AutoCloseable {

    private MemorySegment ownerHandle;
    private final Arena arena = Arena.ofShared();

    private static final Linker LINKER = Linker.nativeLinker();
    private static final SymbolLookup LOOKUP = SymbolLookup.loaderLookup();

    static {
        // Force NativeLib static initialization to load the native library
        // This ensures all FFI symbols are available before we try to look them up.
        // NativeLib is a package-private class, but accessing its class forces
        // its static initializer to run and load the native library.
        try {
            Class.forName("{{ package }}.NativeLib");
        } catch (ClassNotFoundException ignored) {
            // NativeLib not available; native library may be pre-loaded
        }
    }

    // Adapter for handler upcalls: marshals C pointers <-> Java strings
    private static MemorySegment invokeHandlerWithMarshal(
            MemorySegment contextPtr,
            MemorySegment requestPtr,
            Callable handler,
            Arena arena) throws Throwable {
        String requestStr = requestPtr.getString(0);
        String responseStr = handler.handle(requestStr);
        return arena.allocateFrom(responseStr);
    }
