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

static napi_value Add(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0 + value1, &sum);

    return sum;

}

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) {
            // 如需调试可输出 dlerror()
            return false;
        }
    }
    // 必须与 Kotlin 的 @CName("getKotlinGreeting") 完全一致
    g_get_kotlin_greeting = reinterpret_cast<get_kotlin_greeting_t>(
        dlsym(g_lib_handle, "getKotlinGreeting")
    );
    return g_get_kotlin_greeting != nullptr;
}

static napi_value NAPI_Global_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 NAPI_Global_getKotlinGreeting1(napi_env env, napi_callback_info info) {
    // TODO: implements the code;
}
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        {"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"getKotlinGreeting", nullptr, NAPI_Global_getKotlinGreeting, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"getKotlinGreeting", nullptr, NAPI_Global_getKotlinGreeting1, nullptr, nullptr, nullptr, napi_default, nullptr }
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
