#include <jni.h>

#include <dlfcn.h>

#include <cstdint>
#include <cstring>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "mpv_abi.h"

namespace {

constexpr int MPV_EVENT_LOG_MESSAGE = 2;
constexpr int MPV_EVENT_END_FILE = 7;
constexpr int MPV_EVENT_CLIENT_MESSAGE = 16;
constexpr int MPV_EVENT_PROPERTY_CHANGE = 22;
constexpr int MPV_ERROR_UNINITIALIZED = -3;
constexpr int MPV_ERROR_INVALID_PARAMETER = -4;

struct Api {
    mpv_handle *(*create)();
    int (*set_java_vm)(void *, void *);
    int (*initialize)(mpv_handle *);
    int (*set_option_string)(mpv_handle *, const char *, const char *);
    int (*set_option)(mpv_handle *, const char *, int, void *);
    int (*command)(mpv_handle *, const char **);
    int (*get_property)(mpv_handle *, const char *, int, void *);
    int (*set_property)(mpv_handle *, const char *, int, void *);
    int (*set_property_string)(mpv_handle *, const char *, const char *);
    int (*observe_property)(mpv_handle *, std::uint64_t, const char *, int);
    int (*unobserve_property)(mpv_handle *, std::uint64_t);
    int (*request_log_messages)(mpv_handle *, const char *);
    mpv_event *(*wait_event)(mpv_handle *, double);
    const char *(*error_string)(int);
    void (*free_data)(void *);
    void (*wakeup)(mpv_handle *);
    void (*terminate_destroy)(mpv_handle *);
};

struct Context {
    void *library = nullptr;
    Api api{};
    mpv_handle *handle = nullptr;
    jobject surface = nullptr;
    int last_result = 0;
};

thread_local std::string last_error;

template <typename T>
bool resolve(void *library, const char *name, T *target) {
    *target = reinterpret_cast<T>(dlsym(library, name));
    if (*target) return true;
    last_error = "Missing libmpv symbol: ";
    last_error += name;
    return false;
}

bool resolve_api(void *library, Api *api) {
    return resolve(library, "av_jni_set_java_vm", &api->set_java_vm) &&
           resolve(library, "mpv_create", &api->create) &&
           resolve(library, "mpv_initialize", &api->initialize) &&
           resolve(library, "mpv_set_option_string", &api->set_option_string) &&
           resolve(library, "mpv_set_option", &api->set_option) &&
           resolve(library, "mpv_command", &api->command) &&
           resolve(library, "mpv_get_property", &api->get_property) &&
           resolve(library, "mpv_set_property", &api->set_property) &&
           resolve(library, "mpv_set_property_string", &api->set_property_string) &&
           resolve(library, "mpv_observe_property", &api->observe_property) &&
           resolve(library, "mpv_unobserve_property", &api->unobserve_property) &&
           resolve(library, "mpv_request_log_messages", &api->request_log_messages) &&
           resolve(library, "mpv_wait_event", &api->wait_event) &&
           resolve(library, "mpv_error_string", &api->error_string) &&
           resolve(library, "mpv_free", &api->free_data) &&
           resolve(library, "mpv_wakeup", &api->wakeup) &&
           resolve(library, "mpv_terminate_destroy", &api->terminate_destroy);
}

Context *from_handle(jlong value) {
    return reinterpret_cast<Context *>(static_cast<std::intptr_t>(value));
}

jlong to_handle(Context *context) {
    return static_cast<jlong>(reinterpret_cast<std::intptr_t>(context));
}

class UtfChars {
public:
    UtfChars(JNIEnv *env, jstring value) : env_(env), value_(value) {
        chars_ = value ? env->GetStringUTFChars(value, nullptr) : nullptr;
    }

    ~UtfChars() {
        if (chars_) env_->ReleaseStringUTFChars(value_, chars_);
    }

    const char *get() const { return chars_; }

private:
    JNIEnv *env_;
    jstring value_;
    const char *chars_ = nullptr;
};

jstring new_utf8_string(JNIEnv *env, const char *value) {
    if (!value) return nullptr;
    const jsize length = static_cast<jsize>(std::strlen(value));
    jbyteArray bytes = env->NewByteArray(length);
    if (!bytes) return nullptr;
    env->SetByteArrayRegion(bytes, 0, length, reinterpret_cast<const jbyte *>(value));
    jclass string_type = env->FindClass("java/lang/String");
    jstring charset = env->NewStringUTF("UTF-8");
    jmethodID constructor = env->GetMethodID(string_type, "<init>", "([BLjava/lang/String;)V");
    jstring result = static_cast<jstring>(env->NewObject(string_type, constructor, bytes, charset));
    env->DeleteLocalRef(charset);
    env->DeleteLocalRef(string_type);
    env->DeleteLocalRef(bytes);
    return result;
}

jobject box_long(JNIEnv *env, std::int64_t value) {
    jclass type = env->FindClass("java/lang/Long");
    jmethodID method = env->GetStaticMethodID(type, "valueOf", "(J)Ljava/lang/Long;");
    return env->CallStaticObjectMethod(type, method, static_cast<jlong>(value));
}

jobject box_boolean(JNIEnv *env, bool value) {
    jclass type = env->FindClass("java/lang/Boolean");
    jmethodID method = env->GetStaticMethodID(type, "valueOf", "(Z)Ljava/lang/Boolean;");
    return env->CallStaticObjectMethod(type, method, static_cast<jboolean>(value));
}

jobject box_double(JNIEnv *env, double value) {
    jclass type = env->FindClass("java/lang/Double");
    jmethodID method = env->GetStaticMethodID(type, "valueOf", "(D)Ljava/lang/Double;");
    return env->CallStaticObjectMethod(type, method, static_cast<jdouble>(value));
}

jobject property_value(JNIEnv *env, int format, void *data) {
    if (!data) return nullptr;
    switch (format) {
        case MPV_FORMAT_STRING:
        case MPV_FORMAT_OSD_STRING:
            return new_utf8_string(env, static_cast<const char *>(data));
        case MPV_FORMAT_FLAG:
            return box_boolean(env, *static_cast<int *>(data) != 0);
        case MPV_FORMAT_INT64:
            return box_long(env, *static_cast<std::int64_t *>(data));
        case MPV_FORMAT_DOUBLE:
            return box_double(env, *static_cast<double *>(data));
        default:
            return nullptr;
    }
}

jobject read_boxed_value(JNIEnv *env, jobject value, int format, std::int64_t *integer, double *decimal) {
    if (!value) return nullptr;
    switch (format) {
        case MPV_FORMAT_FLAG: {
            jclass type = env->FindClass("java/lang/Boolean");
            jmethodID method = env->GetMethodID(type, "booleanValue", "()Z");
            *integer = env->CallBooleanMethod(value, method) ? 1 : 0;
            return value;
        }
        case MPV_FORMAT_INT64: {
            jclass type = env->FindClass("java/lang/Number");
            jmethodID method = env->GetMethodID(type, "longValue", "()J");
            *integer = env->CallLongMethod(value, method);
            return value;
        }
        case MPV_FORMAT_DOUBLE: {
            jclass type = env->FindClass("java/lang/Number");
            jmethodID method = env->GetMethodID(type, "doubleValue", "()D");
            *decimal = env->CallDoubleMethod(value, method);
            return value;
        }
        default:
            return nullptr;
    }
}

jobjectArray make_string_array(JNIEnv *env, const mpv_event_client_message *message) {
    if (!message || message->num_args <= 0 || !message->args) return nullptr;
    jclass string_type = env->FindClass("java/lang/String");
    jobjectArray result = env->NewObjectArray(message->num_args, string_type, nullptr);
    for (int i = 0; i < message->num_args; ++i) {
        jstring item = new_utf8_string(env, message->args[i]);
        env->SetObjectArrayElement(result, i, item);
        if (item) env->DeleteLocalRef(item);
    }
    return result;
}

jobject make_event(JNIEnv *env, const mpv_event *event) {
    const mpv_event_property *property = nullptr;
    const mpv_event_log_message *log = nullptr;
    const mpv_event_end_file *end_file = nullptr;
    const mpv_event_client_message *client_message = nullptr;

    if (event->event_id == MPV_EVENT_PROPERTY_CHANGE)
        property = static_cast<const mpv_event_property *>(event->data);
    if (event->event_id == MPV_EVENT_LOG_MESSAGE)
        log = static_cast<const mpv_event_log_message *>(event->data);
    if (event->event_id == MPV_EVENT_END_FILE)
        end_file = static_cast<const mpv_event_end_file *>(event->data);
    if (event->event_id == MPV_EVENT_CLIENT_MESSAGE)
        client_message = static_cast<const mpv_event_client_message *>(event->data);

    jstring property_name = property ? new_utf8_string(env, property->name) : nullptr;
    jobject value = property ? property_value(env, property->format, property->data) : nullptr;
    jstring log_prefix = log ? new_utf8_string(env, log->prefix) : nullptr;
    jstring log_text = log ? new_utf8_string(env, log->text) : nullptr;
    jobjectArray arguments = make_string_array(env, client_message);

    jclass type = env->FindClass("io/github/kmpmpv/bridge/MpvNativeEvent");
    jmethodID constructor = env->GetMethodID(
        type,
        "<init>",
        "(IIJLjava/lang/String;Ljava/lang/Object;Ljava/lang/String;ILjava/lang/String;II[Ljava/lang/String;)V");
    jobject result = env->NewObject(
        type,
        constructor,
        event->event_id,
        event->error,
        static_cast<jlong>(event->reply_userdata),
        property_name,
        value,
        log_prefix,
        log ? log->log_level : 0,
        log_text,
        end_file ? end_file->reason : 0,
        end_file ? end_file->error : 0,
        arguments);

    if (property_name) env->DeleteLocalRef(property_name);
    if (value) env->DeleteLocalRef(value);
    if (log_prefix) env->DeleteLocalRef(log_prefix);
    if (log_text) env->DeleteLocalRef(log_text);
    if (arguments) env->DeleteLocalRef(arguments);
    return result;
}

}  // namespace

extern "C" JNIEXPORT jlong JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_create(JNIEnv *env, jclass, jstring library_path) {
    UtfChars requested_path(env, library_path);
    const char *path = requested_path.get() ? requested_path.get() : "libmpv.so";
    void *library = dlopen(path, RTLD_NOW | RTLD_LOCAL);
    if (!library) {
        const char *error = dlerror();
        last_error = error ? error : "dlopen(libmpv) failed";
        return 0;
    }

    std::unique_ptr<Context> context(new Context());
    context->library = library;
    if (!resolve_api(library, &context->api)) {
        dlclose(library);
        return 0;
    }
    JavaVM *java_vm = nullptr;
    if (env->GetJavaVM(&java_vm) != JNI_OK || !java_vm ||
        context->api.set_java_vm(java_vm, nullptr) < 0) {
        last_error = "Failed to register the Android Java VM with libmpv";
        dlclose(library);
        return 0;
    }
    context->handle = context->api.create();
    if (!context->handle) {
        last_error = "mpv_create returned null";
        dlclose(library);
        return 0;
    }
    return to_handle(context.release());
}

extern "C" JNIEXPORT jstring JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_lastError(JNIEnv *env, jclass) {
    return new_utf8_string(env, last_error.c_str());
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_initialize(JNIEnv *, jclass, jlong value) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    return context->api.initialize(context->handle);
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_setOptionString(
    JNIEnv *env, jclass, jlong value, jstring name, jstring option_value) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    UtfChars native_name(env, name);
    UtfChars native_value(env, option_value);
    return context->api.set_option_string(context->handle, native_name.get(), native_value.get());
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_command(
    JNIEnv *env, jclass, jlong value, jobjectArray arguments) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    const jsize count = env->GetArrayLength(arguments);
    std::vector<std::string> strings;
    strings.reserve(static_cast<std::size_t>(count));
    for (jsize i = 0; i < count; ++i) {
        auto item = static_cast<jstring>(env->GetObjectArrayElement(arguments, i));
        {
            UtfChars text(env, item);
            strings.emplace_back(text.get() ? text.get() : "");
        }
        env->DeleteLocalRef(item);
    }
    std::vector<const char *> pointers;
    pointers.reserve(strings.size() + 1);
    for (const std::string &item : strings) pointers.push_back(item.c_str());
    pointers.push_back(nullptr);
    return context->api.command(context->handle, pointers.data());
}

extern "C" JNIEXPORT jobject JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_getProperty(
    JNIEnv *env, jclass, jlong value, jstring name, jint format) {
    Context *context = from_handle(value);
    if (!context) return nullptr;
    UtfChars native_name(env, name);

    if (format == MPV_FORMAT_STRING || format == MPV_FORMAT_OSD_STRING) {
        char *result = nullptr;
        context->last_result = context->api.get_property(
            context->handle, native_name.get(), format, &result);
        if (context->last_result < 0 || !result) return nullptr;
        jstring text = new_utf8_string(env, result);
        context->api.free_data(result);
        return text;
    }
    if (format == MPV_FORMAT_FLAG) {
        int result = 0;
        context->last_result = context->api.get_property(
            context->handle, native_name.get(), format, &result);
        return context->last_result < 0 ? nullptr : box_boolean(env, result != 0);
    }
    if (format == MPV_FORMAT_INT64) {
        std::int64_t result = 0;
        context->last_result = context->api.get_property(
            context->handle, native_name.get(), format, &result);
        return context->last_result < 0 ? nullptr : box_long(env, result);
    }
    if (format == MPV_FORMAT_DOUBLE) {
        double result = 0;
        context->last_result = context->api.get_property(
            context->handle, native_name.get(), format, &result);
        return context->last_result < 0 ? nullptr : box_double(env, result);
    }
    context->last_result = MPV_ERROR_INVALID_PARAMETER;
    return nullptr;
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_lastOperationResult(
    JNIEnv *, jclass, jlong value) {
    Context *context = from_handle(value);
    return context ? context->last_result : MPV_ERROR_UNINITIALIZED;
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_setProperty(
    JNIEnv *env, jclass, jlong value, jstring name, jint format, jobject property_value_object) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    UtfChars native_name(env, name);
    if (format == MPV_FORMAT_STRING || format == MPV_FORMAT_OSD_STRING) {
        UtfChars text(env, static_cast<jstring>(property_value_object));
        return context->api.set_property_string(context->handle, native_name.get(), text.get());
    }
    std::int64_t integer = 0;
    double decimal = 0;
    if (!read_boxed_value(env, property_value_object, format, &integer, &decimal))
        return MPV_ERROR_INVALID_PARAMETER;
    if (format == MPV_FORMAT_FLAG) {
        int flag = integer != 0;
        return context->api.set_property(context->handle, native_name.get(), format, &flag);
    }
    if (format == MPV_FORMAT_INT64)
        return context->api.set_property(context->handle, native_name.get(), format, &integer);
    if (format == MPV_FORMAT_DOUBLE)
        return context->api.set_property(context->handle, native_name.get(), format, &decimal);
    return MPV_ERROR_INVALID_PARAMETER;
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_observeProperty(
    JNIEnv *env, jclass, jlong value, jlong id, jstring name, jint format) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    UtfChars native_name(env, name);
    return context->api.observe_property(context->handle, id, native_name.get(), format);
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_unobserveProperty(
    JNIEnv *, jclass, jlong value, jlong id) {
    Context *context = from_handle(value);
    return context ? context->api.unobserve_property(context->handle, id) : MPV_ERROR_UNINITIALIZED;
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_requestLogMessages(
    JNIEnv *env, jclass, jlong value, jstring level) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    UtfChars native_level(env, level);
    return context->api.request_log_messages(context->handle, native_level.get());
}

extern "C" JNIEXPORT jobject JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_waitEvent(
    JNIEnv *env, jclass, jlong value, jdouble timeout_seconds) {
    Context *context = from_handle(value);
    if (!context) return nullptr;
    mpv_event *event = context->api.wait_event(context->handle, timeout_seconds);
    return event ? make_event(env, event) : nullptr;
}

extern "C" JNIEXPORT jstring JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_errorString(
    JNIEnv *env, jclass, jlong value, jint error_code) {
    Context *context = from_handle(value);
    const char *message = context ? context->api.error_string(error_code) : "mpv client is not initialized";
    return new_utf8_string(env, message ? message : "unknown mpv error");
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_attachSurface(
    JNIEnv *env, jclass, jlong value, jobject surface) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    jobject replacement = env->NewGlobalRef(surface);
    if (!replacement) return MPV_ERROR_INVALID_PARAMETER;
    std::int64_t wid = reinterpret_cast<std::intptr_t>(replacement);
    int result = context->api.set_option(context->handle, "wid", MPV_FORMAT_INT64, &wid);
    if (result < 0) {
        env->DeleteGlobalRef(replacement);
        return result;
    }
    if (context->surface) env->DeleteGlobalRef(context->surface);
    context->surface = replacement;
    return result;
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_detachSurface(
    JNIEnv *env, jclass, jlong value) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    std::int64_t wid = 0;
    int result = context->api.set_option(context->handle, "wid", MPV_FORMAT_INT64, &wid);
    if (result >= 0 && context->surface) {
        env->DeleteGlobalRef(context->surface);
        context->surface = nullptr;
    }
    return result;
}

extern "C" JNIEXPORT void JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_wakeup(JNIEnv *, jclass, jlong value) {
    Context *context = from_handle(value);
    if (context) context->api.wakeup(context->handle);
}

extern "C" JNIEXPORT void JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_destroy(JNIEnv *env, jclass, jlong value) {
    std::unique_ptr<Context> context(from_handle(value));
    if (!context) return;
    // mpv's video output can still use the Surface during termination.
    if (context->handle) context->api.terminate_destroy(context->handle);
    if (context->surface) env->DeleteGlobalRef(context->surface);
    if (context->library) dlclose(context->library);
}
