#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
;
typedef const char* (*get_kotlin_ui_text_t)();
static get_kotlin_ui_text_t g_get_kotlin_ui_text = nullptr;

static bool LoadLibKn() {
    if (g_get_kotlin_greeting && g_get_kotlin_ui_text) 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")
    );
    g_get_kotlin_ui_text = reinterpret_cast<get_kotlin_ui_text_t>(
        dlsym(g_lib_handle, "getKotlinUiText")
    );
    return g_get_kotlin_greeting != nullptr && g_get_kotlin_ui_text != 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 GetKotlinUiText(napi_env env, napi_callback_info /*info*/) {
    if (!LoadLibKn()) {
        napi_throw_error(env, nullptr, "dlopen/dlsym libkn.so|getKotlinUiText 失败");
        return nullptr;
    }
    const char* s = g_get_kotlin_ui_text();
    if (!s) {
        napi_throw_error(env, nullptr, "getKotlinUiText 返回空指针");
        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);
    napi_value fn2;
    napi_create_function(env, "getKotlinUiText", NAPI_AUTO_LENGTH, GetKotlinUiText, nullptr, &fn2);
    napi_set_named_property(env, exports, "getKotlinUiText", fn2);
    return exports;
}

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