#ifndef YOKAN_JVM_BRIDGE_H
#define YOKAN_JVM_BRIDGE_H

#include <dlfcn.h>
#include <TargetConditionals.h>
#include <jni.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

#define YOKAN_CS_OPS_STATUS 0
#define YOKAN_CS_DEBUGGED 0x10000000

extern int csops(pid_t pid, unsigned int ops, void *useraddr, size_t usersize);

static inline int32_t yokan_jvm_has_jit_permission(void) {
#if TARGET_OS_SIMULATOR
    return 1;
#else
    uint32_t flags = 0;
    return csops(getpid(), YOKAN_CS_OPS_STATUS, &flags, sizeof(flags)) == 0 &&
        (flags & YOKAN_CS_DEBUGGED) != 0;
#endif
}

static inline void yokan_jvm_set_error(char *buffer, size_t capacity, const char *message) {
    if (buffer != NULL && capacity > 0) {
        snprintf(buffer, capacity, "%s", message != NULL ? message : "Unknown embedded JVM error");
    }
}

static inline char *yokan_jvm_property(const char *name, const char *value) {
    const size_t size = strlen(name) + strlen(value) + 3;
    char *property = (char *)malloc(size);
    if (property != NULL) {
        snprintf(property, size, "-D%s=%s", name, value);
    }
    return property;
}

static inline void yokan_jvm_set_pending_exception(
    JNIEnv *env,
    char *buffer,
    size_t capacity,
    const char *fallback
) {
    if (!(*env)->ExceptionCheck(env)) {
        yokan_jvm_set_error(buffer, capacity, fallback);
        return;
    }

    jthrowable throwable = (*env)->ExceptionOccurred(env);
    (*env)->ExceptionClear(env);
    jclass throwable_class = throwable == NULL ? NULL :
        (jclass)(*env)->GetObjectClass(env, throwable);
    jmethodID to_string = throwable_class == NULL ? NULL :
        (*env)->GetMethodID(env, throwable_class, "toString", "()Ljava/lang/String;");
    jstring description = to_string == NULL ? NULL :
        (jstring)(*env)->CallObjectMethod(env, throwable, to_string);
    if ((*env)->ExceptionCheck(env)) {
        (*env)->ExceptionClear(env);
        description = NULL;
    }

    int wrote_description = 0;
    if (description != NULL) {
        const char *utf = (*env)->GetStringUTFChars(env, description, NULL);
        if (utf != NULL) {
            yokan_jvm_set_error(buffer, capacity, utf);
            wrote_description = 1;
            (*env)->ReleaseStringUTFChars(env, description, utf);
        }
    }
    if ((*env)->ExceptionCheck(env)) {
        (*env)->ExceptionClear(env);
    }
    if (!wrote_description) {
        yokan_jvm_set_error(buffer, capacity, fallback);
    }
    if (description != NULL) (*env)->DeleteLocalRef(env, description);
    if (throwable_class != NULL) (*env)->DeleteLocalRef(env, throwable_class);
    if (throwable != NULL) (*env)->DeleteLocalRef(env, throwable);
}

static inline jclass yokan_jvm_load_class(
    JNIEnv *env,
    const char *jar_path,
    const char *class_name
) {
    jclass file_class = (*env)->FindClass(env, "java/io/File");
    jmethodID file_constructor = file_class == NULL ? NULL :
        (*env)->GetMethodID(env, file_class, "<init>", "(Ljava/lang/String;)V");
    jstring path = file_constructor == NULL ? NULL : (*env)->NewStringUTF(env, jar_path);
    jobject file = path == NULL ? NULL :
        (*env)->NewObject(env, file_class, file_constructor, path);
    jmethodID to_uri = file == NULL ? NULL :
        (*env)->GetMethodID(env, file_class, "toURI", "()Ljava/net/URI;");
    jobject uri = to_uri == NULL ? NULL : (*env)->CallObjectMethod(env, file, to_uri);

    jclass uri_class = uri == NULL ? NULL : (*env)->FindClass(env, "java/net/URI");
    jmethodID to_url = uri_class == NULL ? NULL :
        (*env)->GetMethodID(env, uri_class, "toURL", "()Ljava/net/URL;");
    jobject url = to_url == NULL ? NULL : (*env)->CallObjectMethod(env, uri, to_url);
    jclass url_class = url == NULL ? NULL : (*env)->FindClass(env, "java/net/URL");
    jobjectArray urls = url_class == NULL ? NULL :
        (*env)->NewObjectArray(env, 1, url_class, url);

    jclass loader_class = urls == NULL ? NULL :
        (*env)->FindClass(env, "java/net/URLClassLoader");
    jmethodID new_loader = loader_class == NULL ? NULL :
        (*env)->GetStaticMethodID(
            env,
            loader_class,
            "newInstance",
            "([Ljava/net/URL;)Ljava/net/URLClassLoader;"
        );
    jobject loader = new_loader == NULL ? NULL :
        (*env)->CallStaticObjectMethod(env, loader_class, new_loader, urls);

    jclass thread_class = loader == NULL ? NULL : (*env)->FindClass(env, "java/lang/Thread");
    jmethodID current_thread = thread_class == NULL ? NULL :
        (*env)->GetStaticMethodID(env, thread_class, "currentThread", "()Ljava/lang/Thread;");
    jobject thread = current_thread == NULL ? NULL :
        (*env)->CallStaticObjectMethod(env, thread_class, current_thread);
    jmethodID set_context_loader = thread == NULL ? NULL :
        (*env)->GetMethodID(
            env,
            thread_class,
            "setContextClassLoader",
            "(Ljava/lang/ClassLoader;)V"
        );
    if (set_context_loader == NULL) {
        return NULL;
    }
    (*env)->CallVoidMethod(env, thread, set_context_loader, loader);

    jclass class_loader_class = (*env)->FindClass(env, "java/lang/ClassLoader");
    jmethodID load_class = class_loader_class == NULL ? NULL :
        (*env)->GetMethodID(
            env,
            class_loader_class,
            "loadClass",
            "(Ljava/lang/String;)Ljava/lang/Class;"
        );
    jstring requested_class = load_class == NULL ? NULL :
        (*env)->NewStringUTF(env, class_name);
    jobject loaded_class = requested_class == NULL ? NULL :
        (*env)->CallObjectMethod(env, loader, load_class, requested_class);
    return (jclass)loaded_class;
}

/*
 * Starts OpenJDK through the JNI invocation API and calls a static
 * main(String[]) method. JLI_Launch cannot be used inside an iOS host app:
 * Apple's libjli startup path resolves the process-wide `main` symbol and
 * would invoke the SwiftUI application entry point a second time.
 */
static inline int32_t yokan_jvm_launch_main(
    const char *jvm_path,
    const char *jar_path,
    const char *main_class_name,
    const char *port,
    const char *temporary_directory,
    const char *user_home,
    int32_t use_mirrored_code_cache,
    char *error_buffer,
    size_t error_capacity
) {
    void *handle = dlopen(jvm_path, RTLD_NOW | RTLD_GLOBAL);
    if (handle == NULL) {
        yokan_jvm_set_error(error_buffer, error_capacity, dlerror());
        return 1;
    }

    typedef jint (*CreateJavaVm)(JavaVM **, void **, void *);
    CreateJavaVm create_vm = (CreateJavaVm)dlsym(handle, "JNI_CreateJavaVM");
    if (create_vm == NULL) {
        yokan_jvm_set_error(error_buffer, error_capacity, "libjvm.dylib does not export JNI_CreateJavaVM");
        return 2;
    }

    char *class_path = yokan_jvm_property("java.class.path", jar_path);
    char *tmp_dir = yokan_jvm_property("java.io.tmpdir", temporary_directory);
    char *home = yokan_jvm_property("user.home", user_home);
    if (class_path == NULL || tmp_dir == NULL || home == NULL) {
        free(class_path);
        free(tmp_dir);
        free(home);
        yokan_jvm_set_error(error_buffer, error_capacity, "Could not allocate embedded JVM options");
        return 3;
    }

    JavaVMOption options[12];
    jint option_count = 0;
    options[option_count++] = (JavaVMOption) { .optionString = "-Xint", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = "-Xms32m", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = "-Xmx512m", .extraInfo = NULL };
    /*
     * HotSpot's compressed class space requires an extended virtual address
     * range that ordinary sideloaded iOS processes do not receive.
     */
    options[option_count++] = (JavaVMOption) { .optionString = "-XX:-UseCompressedClassPointers", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = "-XX:+UnlockExperimentalVMOptions", .extraInfo = NULL };
    if (use_mirrored_code_cache) {
        options[option_count++] = (JavaVMOption) { .optionString = "-XX:+MirrorMappedCodeCache", .extraInfo = NULL };
    }
    options[option_count++] = (JavaVMOption) { .optionString = "-Xrs", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = "-XX:-UsePerfData", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = "-Djava.awt.headless=true", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = class_path, .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = tmp_dir, .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = home, .extraInfo = NULL };
    JavaVMInitArgs init_args = {
        .version = JNI_VERSION_1_8,
        .nOptions = option_count,
        .options = options,
        .ignoreUnrecognized = JNI_FALSE,
    };
    JavaVM *vm = NULL;
    JNIEnv *env = NULL;
    const jint create_result = create_vm(&vm, (void **)&env, &init_args);
    free(class_path);
    free(tmp_dir);
    free(home);
    if (create_result != JNI_OK || vm == NULL || env == NULL) {
        char message[128];
        snprintf(message, sizeof(message), "JNI_CreateJavaVM failed with code %d", create_result);
        yokan_jvm_set_error(error_buffer, error_capacity, message);
        return 4;
    }

    jclass main_class = yokan_jvm_load_class(env, jar_path, main_class_name);
    if (main_class == NULL) {
        yokan_jvm_set_pending_exception(
            env,
            error_buffer,
            error_capacity,
            "Extension server main class was not found"
        );
        return 5;
    }
    jmethodID main_method = (*env)->GetStaticMethodID(env, main_class, "main", "([Ljava/lang/String;)V");
    if (main_method == NULL) {
        yokan_jvm_set_pending_exception(
            env,
            error_buffer,
            error_capacity,
            "Extension server main(String[]) method was not found"
        );
        return 6;
    }
    jclass string_class = (*env)->FindClass(env, "java/lang/String");
    jobjectArray arguments = string_class == NULL ? NULL : (*env)->NewObjectArray(env, 1, string_class, NULL);
    jstring port_argument = arguments == NULL ? NULL : (*env)->NewStringUTF(env, port);
    if (arguments == NULL || port_argument == NULL || (*env)->ExceptionCheck(env)) {
        yokan_jvm_set_pending_exception(
            env,
            error_buffer,
            error_capacity,
            "Could not create extension server arguments"
        );
        return 7;
    }
    (*env)->SetObjectArrayElement(env, arguments, 0, port_argument);
    if ((*env)->ExceptionCheck(env)) {
        yokan_jvm_set_pending_exception(
            env,
            error_buffer,
            error_capacity,
            "Could not populate extension server arguments"
        );
        return 7;
    }
    jvalue call_arguments[1];
    call_arguments[0].l = arguments;
    (*env)->CallStaticVoidMethodA(env, main_class, main_method, call_arguments);
    if ((*env)->ExceptionCheck(env)) {
        yokan_jvm_set_pending_exception(
            env,
            error_buffer,
            error_capacity,
            "Extension server main method failed"
        );
        return 8;
    }
    return 0;
}

#endif
