#include "napi/native_api.h"
#include <dlfcn.h>

static void* g_lib_handle = nullptr;
typedef const char* (*get_kotlin_greeting_t)();
static get_kotlin_greeting_t g_get_kotlin_greeting = nullptr;

static bool LoadLibKn() {
    if (g_get_kotlin_greeting) return true;
    if (!g_lib_handle) {
        g_lib_handle = dlopen("libkn.so", RTLD_LAZY);
        if (!g_lib_handle) {
            return false;
        }
    }
    g_get_kotlin_greeting = reinterpret_cast<get_kotlin_greeting_t>(
        dlsym(g_lib_handle, "getKotlinGreeting")
    );
    return g_get_kotlin_greeting != nullptr;
}

static napi_value GetKotlinGreeting(napi_env env, napi_callback_info /*info*/) {
    if (!LoadLibKn()) {
        napi_throw_error(env, nullptr, "dlopen/dlsym libkn.so|getKotlinGreeting 失败");
        return nullptr;
    }
    const char* s = g_get_kotlin_greeting();
    if (!s) {
        napi_throw_error(env, nullptr, "getKotlinGreeting 返回空指针");
        return nullptr;
    }
    napi_value out;
    napi_create_string_utf8(env, s, NAPI_AUTO_LENGTH, &out);
    return out;
}

static napi_value Init(napi_env env, napi_value exports) {
    // 仅导出 getKotlinGreeting
    napi_value fn;
    napi_create_function(env, "getKotlinGreeting", NAPI_AUTO_LENGTH, GetKotlinGreeting, nullptr, &fn);
    napi_set_named_property(env, exports, "getKotlinGreeting", fn);
    return exports;
}

// 模块名为 libentry，ArkTS 使用 'libentry.so' 导入
NAPI_MODULE(libentry, Init)
