#include <moonbit.h>

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if defined(__APPLE__) || defined(__linux__)
#include <dlfcn.h>
#endif

typedef struct GhosttyTerminalImpl *GhosttyTerminal;
typedef struct GhosttyFormatterImpl *GhosttyFormatter;

typedef struct {
  const uint8_t *ptr;
  size_t len;
} GhosttyString;

typedef struct {
  uint16_t cols;
  uint16_t rows;
  size_t max_scrollback;
} GhosttyTerminalOptions;

typedef enum {
  GHOSTTY_SUCCESS = 0,
  GHOSTTY_OUT_OF_MEMORY = -1,
  GHOSTTY_INVALID_VALUE = -2,
  GHOSTTY_OUT_OF_SPACE = -3,
  GHOSTTY_NO_VALUE = -4,
} GhosttyResult;

typedef enum {
  GHOSTTY_BUILD_INFO_SIMD = 1,
  GHOSTTY_BUILD_INFO_KITTY_GRAPHICS = 2,
  GHOSTTY_BUILD_INFO_TMUX_CONTROL_MODE = 3,
  GHOSTTY_BUILD_INFO_VERSION_STRING = 5,
} GhosttyBuildInfo;

typedef enum {
  GHOSTTY_FORMATTER_FORMAT_PLAIN = 0,
  GHOSTTY_FORMATTER_FORMAT_VT = 1,
  GHOSTTY_FORMATTER_FORMAT_HTML = 2,
} GhosttyFormatterFormat;

typedef struct {
  size_t size;
  bool cursor;
  bool style;
  bool hyperlink;
  bool protection;
  bool kitty_keyboard;
  bool charsets;
} GhosttyFormatterScreenExtra;

typedef struct {
  size_t size;
  bool palette;
  bool modes;
  bool scrolling_region;
  bool tabstops;
  bool pwd;
  bool keyboard;
  GhosttyFormatterScreenExtra screen;
} GhosttyFormatterTerminalExtra;

typedef struct {
  size_t size;
  GhosttyFormatterFormat emit;
  bool unwrap;
  bool trim;
  GhosttyFormatterTerminalExtra extra;
  const void *selection;
} GhosttyFormatterTerminalOptions;

typedef enum {
  GHOSTTY_TERMINAL_DATA_COLS = 1,
  GHOSTTY_TERMINAL_DATA_ROWS = 2,
  GHOSTTY_TERMINAL_DATA_TITLE = 12,
  GHOSTTY_TERMINAL_DATA_PWD = 13,
} GhosttyTerminalData;

typedef GhosttyResult (*ghostty_terminal_new_fn)(
    const void *allocator,
    GhosttyTerminal *terminal,
    GhosttyTerminalOptions options
);
typedef void (*ghostty_terminal_free_fn)(GhosttyTerminal terminal);
typedef void (*ghostty_terminal_reset_fn)(GhosttyTerminal terminal);
typedef GhosttyResult (*ghostty_terminal_resize_fn)(
    GhosttyTerminal terminal,
    uint16_t cols,
    uint16_t rows,
    uint32_t cell_width_px,
    uint32_t cell_height_px
);
typedef void (*ghostty_terminal_vt_write_fn)(
    GhosttyTerminal terminal,
    const uint8_t *data,
    size_t len
);
typedef GhosttyResult (*ghostty_terminal_get_fn)(
    GhosttyTerminal terminal,
    int data,
    void *out
);
typedef GhosttyResult (*ghostty_formatter_terminal_new_fn)(
    const void *allocator,
    GhosttyFormatter *formatter,
    GhosttyTerminal terminal,
    GhosttyFormatterTerminalOptions options
);
typedef GhosttyResult (*ghostty_formatter_format_alloc_fn)(
    GhosttyFormatter formatter,
    const void *allocator,
    uint8_t **out_ptr,
    size_t *out_len
);
typedef void (*ghostty_formatter_free_fn)(GhosttyFormatter formatter);
typedef void (*ghostty_free_fn)(const void *allocator, uint8_t *ptr, size_t len);
typedef GhosttyResult (*ghostty_build_info_fn)(GhosttyBuildInfo data, void *out);

static void *libghostty_handle = NULL;
static char preferred_library_path[1024] = {0};
static char last_error[1024] = "";

static ghostty_terminal_new_fn p_ghostty_terminal_new = NULL;
static ghostty_terminal_free_fn p_ghostty_terminal_free = NULL;
static ghostty_terminal_reset_fn p_ghostty_terminal_reset = NULL;
static ghostty_terminal_resize_fn p_ghostty_terminal_resize = NULL;
static ghostty_terminal_vt_write_fn p_ghostty_terminal_vt_write = NULL;
static ghostty_terminal_get_fn p_ghostty_terminal_get = NULL;
static ghostty_formatter_terminal_new_fn p_ghostty_formatter_terminal_new = NULL;
static ghostty_formatter_format_alloc_fn p_ghostty_formatter_format_alloc = NULL;
static ghostty_formatter_free_fn p_ghostty_formatter_free = NULL;
static ghostty_free_fn p_ghostty_free = NULL;
static ghostty_build_info_fn p_ghostty_build_info = NULL;

static void set_last_error(const char *message) {
  strncpy(last_error, message, sizeof(last_error) - 1);
  last_error[sizeof(last_error) - 1] = '\0';
}

static void set_last_error_code(const char *operation, GhosttyResult result) {
  snprintf(last_error, sizeof(last_error), "%s failed: %d", operation, (int)result);
}

static char *bytes_to_cstring(moonbit_bytes_t bytes) {
  int32_t len = Moonbit_array_length(bytes);
  char *str = (char *)malloc((size_t)len + 1);
  if (str == NULL) {
    return NULL;
  }
  memcpy(str, bytes, (size_t)len);
  str[len] = '\0';
  return str;
}

static moonbit_bytes_t copy_bytes(const uint8_t *ptr, size_t len) {
  moonbit_bytes_t result = moonbit_make_bytes((int32_t)len, 0);
  if (ptr != NULL && len > 0) {
    memcpy(result, ptr, len);
  }
  return result;
}

static moonbit_bytes_t cstring_to_bytes(const char *str) {
  if (str == NULL) {
    return moonbit_make_bytes(0, 0);
  }
  return copy_bytes((const uint8_t *)str, strlen(str));
}

static moonbit_bytes_t ghostty_string_to_bytes(GhosttyString value) {
  if (value.ptr == NULL || value.len == 0) {
    return moonbit_make_bytes(0, 0);
  }
  return copy_bytes(value.ptr, value.len);
}

static void clear_symbols(void) {
  p_ghostty_terminal_new = NULL;
  p_ghostty_terminal_free = NULL;
  p_ghostty_terminal_reset = NULL;
  p_ghostty_terminal_resize = NULL;
  p_ghostty_terminal_vt_write = NULL;
  p_ghostty_terminal_get = NULL;
  p_ghostty_formatter_terminal_new = NULL;
  p_ghostty_formatter_format_alloc = NULL;
  p_ghostty_formatter_free = NULL;
  p_ghostty_free = NULL;
  p_ghostty_build_info = NULL;
}

#if defined(__APPLE__) || defined(__linux__)
static int resolve_symbols(void) {
#define LOAD_SYMBOL(name)                                                           \
  do {                                                                              \
    p_##name = (name##_fn)dlsym(libghostty_handle, #name);                          \
    if (p_##name == NULL) {                                                         \
      set_last_error(dlerror() != NULL ? dlerror() : "failed to resolve symbol");   \
      return 0;                                                                     \
    }                                                                               \
  } while (0)

  LOAD_SYMBOL(ghostty_terminal_new);
  LOAD_SYMBOL(ghostty_terminal_free);
  LOAD_SYMBOL(ghostty_terminal_reset);
  LOAD_SYMBOL(ghostty_terminal_resize);
  LOAD_SYMBOL(ghostty_terminal_vt_write);
  LOAD_SYMBOL(ghostty_terminal_get);
  LOAD_SYMBOL(ghostty_formatter_terminal_new);
  LOAD_SYMBOL(ghostty_formatter_format_alloc);
  LOAD_SYMBOL(ghostty_formatter_free);
  LOAD_SYMBOL(ghostty_free);
  LOAD_SYMBOL(ghostty_build_info);

#undef LOAD_SYMBOL
  return 1;
}

static int try_load_library(const char *path) {
  if (path == NULL || path[0] == '\0') {
    return 0;
  }

  libghostty_handle = dlopen(path, RTLD_LAZY);
  if (libghostty_handle == NULL) {
    return 0;
  }

  if (!resolve_symbols()) {
    dlclose(libghostty_handle);
    libghostty_handle = NULL;
    clear_symbols();
    return 0;
  }

  snprintf(last_error, sizeof(last_error), "loaded %s", path);
  return 1;
}

static int ensure_loaded(void) {
  if (libghostty_handle != NULL) {
    return 1;
  }

  const char *env_path = getenv("LIBGHOSTTY_VT_PATH");
#if defined(__APPLE__)
  const char *defaults[] = {
      preferred_library_path,
      env_path,
      "./vendor/libghostty-vt.dylib",
      "./vendor/libghostty-vt.0.1.0.dylib",
      "libghostty-vt.dylib",
      "libghostty-vt.0.dylib",
      NULL,
  };
#else
  const char *defaults[] = {
      preferred_library_path,
      env_path,
      "./vendor/libghostty-vt.so",
      "./vendor/libghostty-vt.so.0",
      "libghostty-vt.so",
      "libghostty-vt.so.0",
      NULL,
  };
#endif

  for (int i = 0; defaults[i] != NULL; i++) {
    if (try_load_library(defaults[i])) {
      return 1;
    }
  }

  set_last_error("failed to load libghostty-vt; configure a path or set LIBGHOSTTY_VT_PATH");
  return 0;
}
#else
static int ensure_loaded(void) {
  set_last_error("native loading is only implemented for macOS and Linux");
  return 0;
}
#endif

void ghostty_mbt_set_library_path(moonbit_bytes_t path) {
  char *value = bytes_to_cstring(path);
  if (value == NULL) {
    set_last_error("failed to allocate library path");
    return;
  }
  strncpy(preferred_library_path, value, sizeof(preferred_library_path) - 1);
  preferred_library_path[sizeof(preferred_library_path) - 1] = '\0';
  free(value);
}

int32_t ghostty_mbt_load(void) {
  return ensure_loaded() ? 1 : 0;
}

int32_t ghostty_mbt_loaded(void) {
  return libghostty_handle != NULL ? 1 : 0;
}

moonbit_bytes_t ghostty_mbt_last_error(void) {
  return cstring_to_bytes(last_error);
}

GhosttyTerminal ghostty_mbt_terminal_new(
    int32_t cols,
    int32_t rows,
    int64_t max_scrollback
) {
  if (!ensure_loaded()) {
    return NULL;
  }

  GhosttyTerminal terminal = NULL;
  GhosttyTerminalOptions options = {
      .cols = (uint16_t)cols,
      .rows = (uint16_t)rows,
      .max_scrollback = (size_t)max_scrollback,
  };
  GhosttyResult result = p_ghostty_terminal_new(NULL, &terminal, options);
  if (result != GHOSTTY_SUCCESS) {
    set_last_error_code("ghostty_terminal_new", result);
    return NULL;
  }

  return terminal;
}

int32_t ghostty_mbt_terminal_is_null(GhosttyTerminal terminal) {
  return terminal == NULL ? 1 : 0;
}

void ghostty_mbt_terminal_free(GhosttyTerminal terminal) {
  if (terminal == NULL || !ensure_loaded()) {
    return;
  }
  p_ghostty_terminal_free(terminal);
}

void ghostty_mbt_terminal_write(GhosttyTerminal terminal, moonbit_bytes_t data) {
  if (terminal == NULL || !ensure_loaded()) {
    return;
  }
  p_ghostty_terminal_vt_write(
      terminal,
      (const uint8_t *)data,
      (size_t)Moonbit_array_length(data)
  );
}

void ghostty_mbt_terminal_reset(GhosttyTerminal terminal) {
  if (terminal == NULL || !ensure_loaded()) {
    return;
  }
  p_ghostty_terminal_reset(terminal);
}

int32_t ghostty_mbt_terminal_resize(
    GhosttyTerminal terminal,
    int32_t cols,
    int32_t rows,
    int32_t cell_width_px,
    int32_t cell_height_px
) {
  if (terminal == NULL || !ensure_loaded()) {
    return 0;
  }
  GhosttyResult result = p_ghostty_terminal_resize(
      terminal,
      (uint16_t)cols,
      (uint16_t)rows,
      (uint32_t)cell_width_px,
      (uint32_t)cell_height_px
  );
  if (result != GHOSTTY_SUCCESS) {
    set_last_error_code("ghostty_terminal_resize", result);
    return 0;
  }
  return 1;
}

static int32_t terminal_get_int(GhosttyTerminal terminal, GhosttyTerminalData data) {
  if (terminal == NULL || !ensure_loaded()) {
    return 0;
  }
  uint16_t out = 0;
  GhosttyResult result = p_ghostty_terminal_get(terminal, data, &out);
  if (result != GHOSTTY_SUCCESS) {
    set_last_error_code("ghostty_terminal_get", result);
    return 0;
  }
  return (int32_t)out;
}

int32_t ghostty_mbt_terminal_cols(GhosttyTerminal terminal) {
  return terminal_get_int(terminal, GHOSTTY_TERMINAL_DATA_COLS);
}

int32_t ghostty_mbt_terminal_rows(GhosttyTerminal terminal) {
  return terminal_get_int(terminal, GHOSTTY_TERMINAL_DATA_ROWS);
}

static moonbit_bytes_t terminal_get_string(GhosttyTerminal terminal, GhosttyTerminalData data) {
  if (terminal == NULL || !ensure_loaded()) {
    return moonbit_make_bytes(0, 0);
  }
  GhosttyString out = {0};
  GhosttyResult result = p_ghostty_terminal_get(terminal, data, &out);
  if (result == GHOSTTY_NO_VALUE) {
    return moonbit_make_bytes(0, 0);
  }
  if (result != GHOSTTY_SUCCESS) {
    set_last_error_code("ghostty_terminal_get", result);
    return moonbit_make_bytes(0, 0);
  }
  return ghostty_string_to_bytes(out);
}

moonbit_bytes_t ghostty_mbt_terminal_title(GhosttyTerminal terminal) {
  return terminal_get_string(terminal, GHOSTTY_TERMINAL_DATA_TITLE);
}

moonbit_bytes_t ghostty_mbt_terminal_pwd(GhosttyTerminal terminal) {
  return terminal_get_string(terminal, GHOSTTY_TERMINAL_DATA_PWD);
}

moonbit_bytes_t ghostty_mbt_terminal_format(
    GhosttyTerminal terminal,
    int32_t format,
    int32_t trim,
    int32_t unwrap
) {
  if (terminal == NULL || !ensure_loaded()) {
    return moonbit_make_bytes(0, 0);
  }

  GhosttyFormatter formatter = NULL;
  GhosttyFormatterTerminalOptions options;
  memset(&options, 0, sizeof(options));
  options.size = sizeof(options);
  options.emit = (GhosttyFormatterFormat)format;
  options.unwrap = unwrap != 0;
  options.trim = trim != 0;
  options.extra.size = sizeof(options.extra);
  options.extra.screen.size = sizeof(options.extra.screen);

  GhosttyResult result = p_ghostty_formatter_terminal_new(
      NULL,
      &formatter,
      terminal,
      options
  );
  if (result != GHOSTTY_SUCCESS) {
    set_last_error_code("ghostty_formatter_terminal_new", result);
    return moonbit_make_bytes(0, 0);
  }

  uint8_t *buffer = NULL;
  size_t len = 0;
  result = p_ghostty_formatter_format_alloc(formatter, NULL, &buffer, &len);
  if (result != GHOSTTY_SUCCESS) {
    p_ghostty_formatter_free(formatter);
    set_last_error_code("ghostty_formatter_format_alloc", result);
    return moonbit_make_bytes(0, 0);
  }

  moonbit_bytes_t output = copy_bytes(buffer, len);
  p_ghostty_free(NULL, buffer, len);
  p_ghostty_formatter_free(formatter);
  return output;
}

int32_t ghostty_mbt_build_info_bool(int32_t field) {
  if (!ensure_loaded()) {
    return 0;
  }
  bool value = false;
  GhosttyResult result = p_ghostty_build_info((GhosttyBuildInfo)field, &value);
  if (result != GHOSTTY_SUCCESS) {
    set_last_error_code("ghostty_build_info", result);
    return 0;
  }
  return value ? 1 : 0;
}

moonbit_bytes_t ghostty_mbt_build_info_string(int32_t field) {
  if (!ensure_loaded()) {
    return moonbit_make_bytes(0, 0);
  }
  GhosttyString value = {0};
  GhosttyResult result = p_ghostty_build_info((GhosttyBuildInfo)field, &value);
  if (result != GHOSTTY_SUCCESS) {
    set_last_error_code("ghostty_build_info", result);
    return moonbit_make_bytes(0, 0);
  }
  return ghostty_string_to_bytes(value);
}
