// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include "ANSLLM.h"
#include <memory>
#include <unordered_map>
#include <condition_variable>
#include <mutex>
#include <cstdint>

// DebugView: filter on "[ANSLLM]" — gated by ANSCORE_DEBUGVIEW in ANSLicense.h.

// Handle registry with refcount — prevents use-after-free when
// ReleaseANSLLMHandle is called while an operation is still running.
// destructionStarted: set by the first Unregister caller; blocks new Acquires
// and makes subsequent Unregister calls return false without deleting.
// Prevents double-free when Release is raced on the same handle.
struct LLMEntry { int refcount; bool destructionStarted; };
static std::unordered_map<ANSCENTER::ANSLLM*, LLMEntry>& LLMHandleRegistry() {
	static std::unordered_map<ANSCENTER::ANSLLM*, LLMEntry> s;
	return s;
}
static std::mutex& LLMHandleRegistryMutex() {
	static std::mutex m;
	return m;
}
static std::condition_variable& LLMHandleRegistryCV() {
	static std::condition_variable cv;
	return cv;
}

static void RegisterLLMHandle(ANSCENTER::ANSLLM* h) {
	std::lock_guard<std::mutex> lk(LLMHandleRegistryMutex());
	LLMHandleRegistry()[h] = { 1, false };
	ANS_DBG("ANSLLM","Register: handle=%p (uint=%llu) registrySize=%zu",
	       (void*)h, (unsigned long long)(uintptr_t)h, LLMHandleRegistry().size());
}

static ANSCENTER::ANSLLM* AcquireLLMHandle(ANSCENTER::ANSLLM* h) {
	std::lock_guard<std::mutex> lk(LLMHandleRegistryMutex());
	auto it = LLMHandleRegistry().find(h);
	if (it == LLMHandleRegistry().end()) {
		ANS_DBG("ANSLLM","Acquire FAIL: handle=%p (uint=%llu) NOT in registry. registrySize=%zu",
		       (void*)h, (unsigned long long)(uintptr_t)h, LLMHandleRegistry().size());
		size_t i = 0;
		for (auto& kv : LLMHandleRegistry()) {
			ANS_DBG("ANSLLM","  registry[%zu] = %p (uint=%llu) refcount=%d destructionStarted=%d",
			       i++, (void*)kv.first, (unsigned long long)(uintptr_t)kv.first,
			       kv.second.refcount, kv.second.destructionStarted ? 1 : 0);
		}
		return nullptr;
	}
	if (it->second.destructionStarted) {
		ANS_DBG("ANSLLM","Acquire FAIL: handle=%p is being destroyed (destructionStarted=true)", (void*)h);
		return nullptr;
	}
	it->second.refcount++;
	ANS_DBG("ANSLLM","Acquire OK:   handle=%p refcount=%d", (void*)h, it->second.refcount);
	return h;
}

static bool ReleaseLLMHandleRef(ANSCENTER::ANSLLM* h) {
	std::lock_guard<std::mutex> lk(LLMHandleRegistryMutex());
	auto it = LLMHandleRegistry().find(h);
	if (it == LLMHandleRegistry().end()) return false;
	it->second.refcount--;
	if (it->second.refcount <= 0) {
		LLMHandleRegistryCV().notify_all();
	}
	return false;  // Only Unregister deletes.
}

static bool UnregisterLLMHandle(ANSCENTER::ANSLLM* h) {
	std::unique_lock<std::mutex> lk(LLMHandleRegistryMutex());
	auto it = LLMHandleRegistry().find(h);
	if (it == LLMHandleRegistry().end()) {
		ANS_DBG("ANSLLM","Unregister: handle=%p NOT in registry (already gone)", (void*)h);
		return false;
	}
	if (it->second.destructionStarted) {
		ANS_DBG("ANSLLM","Unregister: handle=%p already being destroyed by another thread, returning false", (void*)h);
		return false;  // Another thread already owns the delete.
	}
	ANS_DBG("ANSLLM","Unregister: handle=%p starting (refcount before=%d)", (void*)h, it->second.refcount);
	it->second.destructionStarted = true;
	it->second.refcount--;
	bool ok = LLMHandleRegistryCV().wait_for(lk, std::chrono::seconds(30), [&]() {
		auto it2 = LLMHandleRegistry().find(h);
		return it2 == LLMHandleRegistry().end() || it2->second.refcount <= 0;
	});
	if (!ok) {
		ANS_DBG("ANSLLM","WARNING: Unregister timed out waiting for in-flight operations on handle=%p", (void*)h);
		OutputDebugStringA("WARNING: UnregisterLLMHandle timed out waiting for in-flight operations\n");
	}
	LLMHandleRegistry().erase(h);
	return true;
}

// RAII guard — ensures ReleaseLLMHandleRef is always called
class LLMHandleGuard {
	ANSCENTER::ANSLLM* engine;
public:
	explicit LLMHandleGuard(ANSCENTER::ANSLLM* e) : engine(e) {}
	~LLMHandleGuard() { if (engine) ReleaseLLMHandleRef(engine); }
	ANSCENTER::ANSLLM* get() const { return engine; }
	explicit operator bool() const { return engine != nullptr; }
	LLMHandleGuard(const LLMHandleGuard&) = delete;
	LLMHandleGuard& operator=(const LLMHandleGuard&) = delete;
};

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     ) noexcept
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

// Helper: safely copy a std::string into a LabVIEW LStrHandle.
// Returns 1 on success, 0 on failure (empty string or allocation error).
static int CopyToLStrHandle(LStrHandle handle, const std::string& str) noexcept {
    if (str.empty() || handle == nullptr) return 0;
    const auto size = static_cast<int32>(str.length());
    MgErr error = DSSetHandleSize(handle, sizeof(int32) + size * sizeof(uChar));
    if (error != noErr) return 0;
    (*handle)->cnt = size;
    memcpy((*handle)->str, str.c_str(), static_cast<size_t>(size));
    return 1;
}

extern "C" ANSLLM_API int  CreateANSLLMHandle(ANSCENTER::ANSLLM** Handle, const char* licenseKey, int localLLM) {
    ANS_DBG("ANSLLM","Create called: HandlePtr=%p, *Handle(in)=%p, localLLM=%d",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), localLLM);
    if (Handle == nullptr) { ANS_DBG("ANSLLM","Create FAIL: Handle is null"); return 0; }
    if (licenseKey == nullptr) { ANS_DBG("ANSLLM","Create FAIL: licenseKey is null"); return 0; }
    try {
        // Pure constructor: ignore *Handle(in). LabVIEW's CLF Node marshalling
        // reuses the same temp buffer per call site, so *Handle(in) often holds
        // leftover bytes from the previous Create's output even when the actual
        // LabVIEW wire is a different, freshly-allocated instance. Inspecting
        // *Handle(in) and destroying what we "see" tears down legitimate
        // parallel instances. (Same reasoning as CreateANSAWSHandle.)
        // Trade-off: a true double-Create on the same wire leaks the prior
        // handle -- caller's bug; the alternative is far worse.
        *Handle = nullptr;

        // std::unique_ptr ensures automatic cleanup on any failure path
        auto ptr = std::make_unique<ANSCENTER::ANSLLM>();
        ANS_DBG("ANSLLM","Create: allocated handle=%p (uint=%llu), calling Initialize...",
               (void*)ptr.get(), (unsigned long long)(uintptr_t)ptr.get());
        if (!ptr->Initialize(licenseKey, localLLM != 0)) {
            // unique_ptr automatically deletes — no leak
            ANS_DBG("ANSLLM","Create FAIL: Initialize returned false, handle=%p auto-deleted", (void*)ptr.get());
            *Handle = nullptr;
            return 0;
        }
        // Transfer ownership to caller on success
        *Handle = ptr.release();
        RegisterLLMHandle(*Handle);
        ANS_DBG("ANSLLM","Create OK: handle=%p (uint=%llu)", (void*)*Handle, (unsigned long long)(uintptr_t)*Handle);
        return 1;
    }
    catch (const std::exception& e) {
        ANS_DBG("ANSLLM","Create EXCEPTION (std::exception): %s", e.what());
        *Handle = nullptr;
        return 0;
    }
    catch (...) {
        ANS_DBG("ANSLLM","Create EXCEPTION (unknown)");
        *Handle = nullptr;
        return 0;
    }
}
static int ReleaseANSLLMHandle_Impl(ANSCENTER::ANSLLM** Handle) {
    try {
        if (!Handle || !*Handle) {
            ANS_DBG("ANSLLM","Release: HandlePtr or *Handle is null, no-op");
            return 1;
        }
        ANSCENTER::ANSLLM* h = *Handle;
        ANS_DBG("ANSLLM","Release called: handle=%p (uint=%llu)", (void*)h, (unsigned long long)(uintptr_t)h);
        if (!UnregisterLLMHandle(h)) {
            ANS_DBG("ANSLLM","Release: Unregister returned false (already gone or being destroyed by another thread), handle=%p", (void*)h);
            *Handle = nullptr;
            return 1;
        }
        delete h;
        *Handle = nullptr;
        ANS_DBG("ANSLLM","Release OK: handle=%p deleted, registry now has %zu entries",
               (void*)h, LLMHandleRegistry().size());
        return 1;
    }
    catch (...) {
        ANS_DBG("ANSLLM","Release EXCEPTION (unknown)");
        if (Handle) *Handle = nullptr;
        return 0;
    }
}

extern "C" ANSLLM_API int  ReleaseANSLLMHandle(ANSCENTER::ANSLLM** Handle) {
    __try {
        return ReleaseANSLLMHandle_Impl(Handle);
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        ANS_DBG("ANSLLM","ReleaseANSLLMHandle: SEH exception caught");
        if (Handle) *Handle = nullptr;
        return 0;
    }
}

extern "C" ANSLLM_API int  SetANSLLMProvider(ANSCENTER::ANSLLM** Handle, const char* provider) {
    ANS_DBG("ANSLLM","SetANSLLMProvider: HandlePtr=%p, *Handle=%p, provider=%s",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), provider ? provider : "(null)");
    if (Handle == nullptr || *Handle == nullptr || provider == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetLLMProvider(provider) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  GetANSLLMProvider(ANSCENTER::ANSLLM** Handle, LStrHandle provider) {
    ANS_DBG("ANSLLM","GetANSLLMProvider: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return CopyToLStrHandle(provider, guard.get()->GetLLMProvider());
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}

extern "C" ANSLLM_API int  SetApiKey(ANSCENTER::ANSLLM** Handle, const char* apiKey) {
    ANS_DBG("ANSLLM","SetApiKey: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr || apiKey == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetApiKey(apiKey) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}


extern "C" ANSLLM_API int  ANSLLMGetModelList(ANSCENTER::ANSLLM** Handle, LStrHandle modelList) {
    ANS_DBG("ANSLLM","ANSLLMGetModelList: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        std::vector<std::string> models = guard.get()->GetModelList();
        std::string st;
        for (size_t i = 0; i < models.size(); ++i) {
            if (i > 0) st += ";";
            st += models[i];
        }
        return CopyToLStrHandle(modelList, st);
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetTranscriptMode(ANSCENTER::ANSLLM** Handle, int transcriptMode) {
    ANS_DBG("ANSLLM","ANSLLMSetTranscriptMode: HandlePtr=%p, *Handle=%p, transcriptMode=%d",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), transcriptMode);
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetTranscriptMode(transcriptMode == 1) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetModel(ANSCENTER::ANSLLM** Handle, const char* modelName) {
    ANS_DBG("ANSLLM","ANSLLMSetModel: HandlePtr=%p, *Handle=%p, modelName=%s",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), modelName ? modelName : "(null)");
    if (Handle == nullptr || *Handle == nullptr || modelName == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetModel(modelName) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}

extern "C" ANSLLM_API int  ANSLLMInputAddText(ANSCENTER::ANSLLM** Handle, const char* inputText) {
    ANS_DBG("ANSLLM","ANSLLMInputAddText: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr || inputText == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->InputAddText(inputText) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMInputAddImageUrl(ANSCENTER::ANSLLM** Handle, const char* imageURL, const char* summary) {
    ANS_DBG("ANSLLM","ANSLLMInputAddImageUrl: HandlePtr=%p, *Handle=%p, imageURL=%s",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), imageURL ? imageURL : "(null)");
    if (Handle == nullptr || *Handle == nullptr || imageURL == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        const char* safeSummary = (summary != nullptr) ? summary : "";
        return guard.get()->InputAddImageUrl(imageURL, safeSummary) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMInputAddImageFromPath(ANSCENTER::ANSLLM** Handle, const char* filePath, const char* summary) {
    ANS_DBG("ANSLLM","ANSLLMInputAddImageFromPath: HandlePtr=%p, *Handle=%p, filePath=%s",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), filePath ? filePath : "(null)");
    if (Handle == nullptr || *Handle == nullptr || filePath == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        const char* safeSummary = (summary != nullptr) ? summary : "";
        return guard.get()->InputAddImageFromPath(filePath, safeSummary) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMInputAddImageFromBase64(ANSCENTER::ANSLLM** Handle, const char* base64Image, const char* summary) {
    ANS_DBG("ANSLLM","ANSLLMInputAddImageFromBase64: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr || base64Image == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        const char* safeSummary = (summary != nullptr) ? summary : "";
        return guard.get()->InputAddImageFromBase64(base64Image, safeSummary) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMInputAddFileURL(ANSCENTER::ANSLLM** Handle, const char* fileURL, const char* summary) {
    ANS_DBG("ANSLLM","ANSLLMInputAddFileURL: HandlePtr=%p, *Handle=%p, fileURL=%s",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), fileURL ? fileURL : "(null)");
    if (Handle == nullptr || *Handle == nullptr || fileURL == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        const char* safeSummary = (summary != nullptr) ? summary : "";
        return guard.get()->InputAddFileURL(fileURL, safeSummary) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMInputAddFileData(ANSCENTER::ANSLLM** Handle, const char* filePath, const char* summary) {
    ANS_DBG("ANSLLM","ANSLLMInputAddFileData: HandlePtr=%p, *Handle=%p, filePath=%s",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), filePath ? filePath : "(null)");
    if (Handle == nullptr || *Handle == nullptr || filePath == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        const char* safeSummary = (summary != nullptr) ? summary : "";
        return guard.get()->InputAddFileData(filePath, safeSummary) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMCreateConversation(ANSCENTER::ANSLLM** Handle, const char* systemMessage, const char* developerMessage, const char* conversationName) {
    ANS_DBG("ANSLLM","ANSLLMCreateConversation: HandlePtr=%p, *Handle=%p, conversationName=%s",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), conversationName ? conversationName : "(null)");
    if (Handle == nullptr || *Handle == nullptr) return 0;
    if (systemMessage == nullptr || developerMessage == nullptr || conversationName == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->CreateConversation(systemMessage, developerMessage, conversationName) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetConversation(ANSCENTER::ANSLLM** Handle, const char* conversationName) {
    ANS_DBG("ANSLLM","ANSLLMSetConversation: HandlePtr=%p, *Handle=%p, conversationName=%s",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), conversationName ? conversationName : "(null)");
    if (Handle == nullptr || *Handle == nullptr || conversationName == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetConversation(conversationName) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMAsk(ANSCENTER::ANSLLM** Handle, const char* prompt, LStrHandle response) {
    ANS_DBG("ANSLLM","ANSLLMAsk: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr || prompt == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return CopyToLStrHandle(response, guard.get()->Ask(prompt));
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}

extern "C" ANSLLM_API int  ANSLLMClearInput(ANSCENTER::ANSLLM** Handle) {
    ANS_DBG("ANSLLM","ANSLLMClearInput: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->ClearInputs() ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetConversationList(ANSCENTER::ANSLLM** Handle, LStrHandle conversationList) {
    ANS_DBG("ANSLLM","ANSLLMGetConversationList: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        std::vector<std::string> convs = guard.get()->GetConversationList();
        std::string st;
        for (size_t i = 0; i < convs.size(); ++i) {
            if (i > 0) st += ";";
            st += convs[i];
        }
        return CopyToLStrHandle(conversationList, st);
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMDeleteConversation(ANSCENTER::ANSLLM** Handle, const char* conversationName) {
    ANS_DBG("ANSLLM","ANSLLMDeleteConversation: HandlePtr=%p, *Handle=%p, conversationName=%s",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), conversationName ? conversationName : "(null)");
    if (Handle == nullptr || *Handle == nullptr || conversationName == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->DeleteConversation(conversationName) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetUTF8(ANSCENTER::ANSLLM** Handle, int utf8Mode) {
    ANS_DBG("ANSLLM","ANSLLMSetUTF8: HandlePtr=%p, *Handle=%p, utf8Mode=%d",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), utf8Mode);
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetUTF8(utf8Mode == 1) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetUTF8(ANSCENTER::ANSLLM** Handle) {
    ANS_DBG("ANSLLM","ANSLLMGetUTF8: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->GetUTF8() ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMPollAi(ANSCENTER::ANSLLM** Handle, int abort) {
    ANS_DBG("ANSLLM","ANSLLMPollAi: HandlePtr=%p, *Handle=%p, abort=%d",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), abort);
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->PollAi(abort != 0);
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}

extern "C" ANSLLM_API int  ANSLLMSetLocalLLM(ANSCENTER::ANSLLM** Handle, int localLLM) {
    ANS_DBG("ANSLLM","ANSLLMSetLocalLLM: HandlePtr=%p, *Handle=%p, localLLM=%d",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), localLLM);
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetLocalLLM(localLLM != 0) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetOllamaBaseUrl(ANSCENTER::ANSLLM** Handle, const char* baseUrl) {
    ANS_DBG("ANSLLM","ANSLLMSetOllamaBaseUrl: HandlePtr=%p, *Handle=%p, baseUrl=%s",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), baseUrl ? baseUrl : "(null)");
    if (Handle == nullptr || *Handle == nullptr || baseUrl == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetOllamaBaseUrl(baseUrl) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetBaseURL(ANSCENTER::ANSLLM** Handle, const char* baseURL) {
    ANS_DBG("ANSLLM","ANSLLMSetBaseURL: HandlePtr=%p, *Handle=%p, baseURL=%s",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), baseURL ? baseURL : "(null)");
    if (Handle == nullptr || *Handle == nullptr || baseURL == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetBaseURL(baseURL) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetHeartbeatMs(ANSCENTER::ANSLLM** Handle, int heartbeatMs) {
    ANS_DBG("ANSLLM","ANSLLMSetHeartbeatMs: HandlePtr=%p, *Handle=%p, heartbeatMs=%d",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), heartbeatMs);
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetHeartbeatMs(heartbeatMs) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetHeartbeatMs(ANSCENTER::ANSLLM** Handle) {
    ANS_DBG("ANSLLM","ANSLLMGetHeartbeatMs: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return -1;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return -1;
    try {
        return guard.get()->GetHeartbeatMs();
    }
    catch (const std::exception&) {
        return -1;
    }
    catch (...) {
        return -1;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetHostedConversation(ANSCENTER::ANSLLM** Handle, int hostedConversationMode) {
    ANS_DBG("ANSLLM","ANSLLMSetHostedConversation: HandlePtr=%p, *Handle=%p, hostedConversationMode=%d",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), hostedConversationMode);
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetHostedConversation(hostedConversationMode == 1) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetHostedConversation(ANSCENTER::ANSLLM** Handle) {
    ANS_DBG("ANSLLM","ANSLLMGetHostedConversation: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->GetHostedConversation() ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetStreamingMode(ANSCENTER::ANSLLM** Handle) {
    ANS_DBG("ANSLLM","ANSLLMGetStreamingMode: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->GetStreamingMode() ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetStreamingMode(ANSCENTER::ANSLLM** Handle, int streamingMode) {
    ANS_DBG("ANSLLM","ANSLLMSetStreamingMode: HandlePtr=%p, *Handle=%p, streamingMode=%d",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), streamingMode);
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetStreamingMode(streamingMode == 1) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetIdleTimeoutMs(ANSCENTER::ANSLLM** Handle) {
    ANS_DBG("ANSLLM","ANSLLMGetIdleTimeoutMs: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return -1;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return -1;
    try {
        return guard.get()->GetIdleTimeoutMs();
    }
    catch (const std::exception&) {
        return -1;
    }
    catch (...) {
        return -1;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetIdleTimeoutMs(ANSCENTER::ANSLLM** Handle, int idleTimeoutMs) {
    ANS_DBG("ANSLLM","ANSLLMSetIdleTimeoutMs: HandlePtr=%p, *Handle=%p, idleTimeoutMs=%d",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), idleTimeoutMs);
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetIdleTimeoutMs(idleTimeoutMs) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}

extern "C" ANSLLM_API int  ANSLLMSetSleepMs(ANSCENTER::ANSLLM** Handle, int sleepMs) {
    ANS_DBG("ANSLLM","ANSLLMSetSleepMs: HandlePtr=%p, *Handle=%p, sleepMs=%d",
           (void*)Handle, (void*)(Handle ? *Handle : nullptr), sleepMs);
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return guard.get()->SetSleepMs(sleepMs) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetLastErrorMessage(ANSCENTER::ANSLLM** Handle, LStrHandle LastErrorMessage) {
    ANS_DBG("ANSLLM","ANSLLMGetLastErrorMessage: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return CopyToLStrHandle(LastErrorMessage, guard.get()->GetLastErrorMessage());
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetOutputText(ANSCENTER::ANSLLM** Handle, LStrHandle outputText) {
    ANS_DBG("ANSLLM","ANSLLMGetOutputText: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return CopyToLStrHandle(outputText, guard.get()->GetOutputText());
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetOutputTextSb(ANSCENTER::ANSLLM** Handle, LStrHandle outputTextSb) {
    ANS_DBG("ANSLLM","ANSLLMGetOutputTextSb: HandlePtr=%p, *Handle=%p", (void*)Handle, (void*)(Handle ? *Handle : nullptr));
    if (Handle == nullptr || *Handle == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(*Handle));
    if (!guard) return 0;
    try {
        return CopyToLStrHandle(outputTextSb, guard.get()->GetOutputTextSb());
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}

// ============================================================================
// V2 entry points — accept uint64_t handleVal by value instead of ANSLLM**
// to eliminate the LabVIEW buffer reuse bug when concurrent calls share the
// same Handle** buffer address.
// ============================================================================

extern "C" ANSLLM_API int  SetANSLLMProvider_V2(uint64_t handleVal, const char* provider) {
    ANS_DBG("ANSLLM","SetANSLLMProvider_V2: handleVal=%llu, provider=%s",
           (unsigned long long)handleVal, provider ? provider : "(null)");
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetLLMProvider(provider) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  GetANSLLMProvider_V2(uint64_t handleVal, LStrHandle provider) {
    ANS_DBG("ANSLLM","GetANSLLMProvider_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return CopyToLStrHandle(provider, guard.get()->GetLLMProvider());
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  SetApiKey_V2(uint64_t handleVal, const char* apiKey) {
    ANS_DBG("ANSLLM","SetApiKey_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetApiKey(apiKey) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetModelList_V2(uint64_t handleVal, LStrHandle modelList) {
    ANS_DBG("ANSLLM","ANSLLMGetModelList_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        std::vector<std::string> models = guard.get()->GetModelList();
        std::string st;
        for (size_t i = 0; i < models.size(); ++i) {
            if (i > 0) st += ";";
            st += models[i];
        }
        return CopyToLStrHandle(modelList, st);
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetTranscriptMode_V2(uint64_t handleVal, int transcriptMode) {
    ANS_DBG("ANSLLM","ANSLLMSetTranscriptMode_V2: handleVal=%llu, transcriptMode=%d",
           (unsigned long long)handleVal, transcriptMode);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetTranscriptMode(transcriptMode == 1) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetModel_V2(uint64_t handleVal, const char* modelName) {
    ANS_DBG("ANSLLM","ANSLLMSetModel_V2: handleVal=%llu, modelName=%s",
           (unsigned long long)handleVal, modelName ? modelName : "(null)");
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetModel(modelName) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMInputAddText_V2(uint64_t handleVal, const char* inputText) {
    ANS_DBG("ANSLLM","ANSLLMInputAddText_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->InputAddText(inputText) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMInputAddImageUrl_V2(uint64_t handleVal, const char* imageURL, const char* summary) {
    ANS_DBG("ANSLLM","ANSLLMInputAddImageUrl_V2: handleVal=%llu, imageURL=%s",
           (unsigned long long)handleVal, imageURL ? imageURL : "(null)");
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        const char* safeSummary = (summary != nullptr) ? summary : "";
        return guard.get()->InputAddImageUrl(imageURL, safeSummary) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMInputAddImageFromPath_V2(uint64_t handleVal, const char* filePath, const char* summary) {
    ANS_DBG("ANSLLM","ANSLLMInputAddImageFromPath_V2: handleVal=%llu, filePath=%s",
           (unsigned long long)handleVal, filePath ? filePath : "(null)");
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        const char* safeSummary = (summary != nullptr) ? summary : "";
        return guard.get()->InputAddImageFromPath(filePath, safeSummary) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMInputAddImageFromBase64_V2(uint64_t handleVal, const char* base64Image, const char* summary) {
    ANS_DBG("ANSLLM","ANSLLMInputAddImageFromBase64_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        const char* safeSummary = (summary != nullptr) ? summary : "";
        return guard.get()->InputAddImageFromBase64(base64Image, safeSummary) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMInputAddFileURL_V2(uint64_t handleVal, const char* fileURL, const char* summary) {
    ANS_DBG("ANSLLM","ANSLLMInputAddFileURL_V2: handleVal=%llu, fileURL=%s",
           (unsigned long long)handleVal, fileURL ? fileURL : "(null)");
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        const char* safeSummary = (summary != nullptr) ? summary : "";
        return guard.get()->InputAddFileURL(fileURL, safeSummary) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMInputAddFileData_V2(uint64_t handleVal, const char* filePath, const char* summary) {
    ANS_DBG("ANSLLM","ANSLLMInputAddFileData_V2: handleVal=%llu, filePath=%s",
           (unsigned long long)handleVal, filePath ? filePath : "(null)");
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        const char* safeSummary = (summary != nullptr) ? summary : "";
        return guard.get()->InputAddFileData(filePath, safeSummary) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMClearInput_V2(uint64_t handleVal) {
    ANS_DBG("ANSLLM","ANSLLMClearInput_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->ClearInputs() ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMCreateConversation_V2(uint64_t handleVal, const char* systemMessage, const char* developerMessage, const char* conversationName) {
    ANS_DBG("ANSLLM","ANSLLMCreateConversation_V2: handleVal=%llu, conversationName=%s",
           (unsigned long long)handleVal, conversationName ? conversationName : "(null)");
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    if (systemMessage == nullptr || developerMessage == nullptr || conversationName == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->CreateConversation(systemMessage, developerMessage, conversationName) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetConversation_V2(uint64_t handleVal, const char* conversationName) {
    ANS_DBG("ANSLLM","ANSLLMSetConversation_V2: handleVal=%llu, conversationName=%s",
           (unsigned long long)handleVal, conversationName ? conversationName : "(null)");
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    if (conversationName == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetConversation(conversationName) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMDeleteConversation_V2(uint64_t handleVal, const char* conversationName) {
    ANS_DBG("ANSLLM","ANSLLMDeleteConversation_V2: handleVal=%llu, conversationName=%s",
           (unsigned long long)handleVal, conversationName ? conversationName : "(null)");
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    if (conversationName == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->DeleteConversation(conversationName) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetConversationList_V2(uint64_t handleVal, LStrHandle conversationList) {
    ANS_DBG("ANSLLM","ANSLLMGetConversationList_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        std::vector<std::string> convs = guard.get()->GetConversationList();
        std::string st;
        for (size_t i = 0; i < convs.size(); ++i) {
            if (i > 0) st += ";";
            st += convs[i];
        }
        return CopyToLStrHandle(conversationList, st);
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMAsk_V2(uint64_t handleVal, const char* prompt, LStrHandle response) {
    ANS_DBG("ANSLLM","ANSLLMAsk_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    if (prompt == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return CopyToLStrHandle(response, guard.get()->Ask(prompt));
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMPollAi_V2(uint64_t handleVal, int abort) {
    ANS_DBG("ANSLLM","ANSLLMPollAi_V2: handleVal=%llu, abort=%d",
           (unsigned long long)handleVal, abort);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->PollAi(abort != 0);
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetUTF8_V2(uint64_t handleVal, int utf8Mode) {
    ANS_DBG("ANSLLM","ANSLLMSetUTF8_V2: handleVal=%llu, utf8Mode=%d",
           (unsigned long long)handleVal, utf8Mode);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetUTF8(utf8Mode == 1) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetUTF8_V2(uint64_t handleVal) {
    ANS_DBG("ANSLLM","ANSLLMGetUTF8_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->GetUTF8() ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetLocalLLM_V2(uint64_t handleVal, int localLLM) {
    ANS_DBG("ANSLLM","ANSLLMSetLocalLLM_V2: handleVal=%llu, localLLM=%d",
           (unsigned long long)handleVal, localLLM);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetLocalLLM(localLLM != 0) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetOllamaBaseUrl_V2(uint64_t handleVal, const char* baseUrl) {
    ANS_DBG("ANSLLM","ANSLLMSetOllamaBaseUrl_V2: handleVal=%llu, baseUrl=%s",
           (unsigned long long)handleVal, baseUrl ? baseUrl : "(null)");
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    if (baseUrl == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetOllamaBaseUrl(baseUrl) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetBaseURL_V2(uint64_t handleVal, const char* baseURL) {
    ANS_DBG("ANSLLM","ANSLLMSetBaseURL_V2: handleVal=%llu, baseURL=%s",
           (unsigned long long)handleVal, baseURL ? baseURL : "(null)");
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    if (baseURL == nullptr) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetBaseURL(baseURL) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetHeartbeatMs_V2(uint64_t handleVal, int heartbeatMs) {
    ANS_DBG("ANSLLM","ANSLLMSetHeartbeatMs_V2: handleVal=%llu, heartbeatMs=%d",
           (unsigned long long)handleVal, heartbeatMs);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetHeartbeatMs(heartbeatMs) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetHeartbeatMs_V2(uint64_t handleVal) {
    ANS_DBG("ANSLLM","ANSLLMGetHeartbeatMs_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return -1;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return -1;
    try {
        return guard.get()->GetHeartbeatMs();
    }
    catch (const std::exception&) {
        return -1;
    }
    catch (...) {
        return -1;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetHostedConversation_V2(uint64_t handleVal, int hostedConversationMode) {
    ANS_DBG("ANSLLM","ANSLLMSetHostedConversation_V2: handleVal=%llu, hostedConversationMode=%d",
           (unsigned long long)handleVal, hostedConversationMode);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetHostedConversation(hostedConversationMode == 1) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetHostedConversation_V2(uint64_t handleVal) {
    ANS_DBG("ANSLLM","ANSLLMGetHostedConversation_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->GetHostedConversation() ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetStreamingMode_V2(uint64_t handleVal) {
    ANS_DBG("ANSLLM","ANSLLMGetStreamingMode_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->GetStreamingMode() ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetStreamingMode_V2(uint64_t handleVal, int streamingMode) {
    ANS_DBG("ANSLLM","ANSLLMSetStreamingMode_V2: handleVal=%llu, streamingMode=%d",
           (unsigned long long)handleVal, streamingMode);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetStreamingMode(streamingMode == 1) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetIdleTimeoutMs_V2(uint64_t handleVal) {
    ANS_DBG("ANSLLM","ANSLLMGetIdleTimeoutMs_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return -1;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return -1;
    try {
        return guard.get()->GetIdleTimeoutMs();
    }
    catch (const std::exception&) {
        return -1;
    }
    catch (...) {
        return -1;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetIdleTimeoutMs_V2(uint64_t handleVal, int idleTimeoutMs) {
    ANS_DBG("ANSLLM","ANSLLMSetIdleTimeoutMs_V2: handleVal=%llu, idleTimeoutMs=%d",
           (unsigned long long)handleVal, idleTimeoutMs);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetIdleTimeoutMs(idleTimeoutMs) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMSetSleepMs_V2(uint64_t handleVal, int sleepMs) {
    ANS_DBG("ANSLLM","ANSLLMSetSleepMs_V2: handleVal=%llu, sleepMs=%d",
           (unsigned long long)handleVal, sleepMs);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return guard.get()->SetSleepMs(sleepMs) ? 1 : 0;
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetLastErrorMessage_V2(uint64_t handleVal, LStrHandle LastErrorMessage) {
    ANS_DBG("ANSLLM","ANSLLMGetLastErrorMessage_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return CopyToLStrHandle(LastErrorMessage, guard.get()->GetLastErrorMessage());
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetOutputText_V2(uint64_t handleVal, LStrHandle outputText) {
    ANS_DBG("ANSLLM","ANSLLMGetOutputText_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return CopyToLStrHandle(outputText, guard.get()->GetOutputText());
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
extern "C" ANSLLM_API int  ANSLLMGetOutputTextSb_V2(uint64_t handleVal, LStrHandle outputTextSb) {
    ANS_DBG("ANSLLM","ANSLLMGetOutputTextSb_V2: handleVal=%llu", (unsigned long long)handleVal);
    auto* _v2h = reinterpret_cast<ANSCENTER::ANSLLM*>(handleVal); if (!_v2h) return 0;
    LLMHandleGuard guard(AcquireLLMHandle(_v2h));
    if (!guard) return 0;
    try {
        return CopyToLStrHandle(outputTextSb, guard.get()->GetOutputTextSb());
    }
    catch (const std::exception&) {
        return 0;
    }
    catch (...) {
        return 0;
    }
}
