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

typedef struct MockTerminal *GhosttyTerminal;
typedef struct MockFormatter *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_TERMINAL_DATA_COLS = 1,
  GHOSTTY_TERMINAL_DATA_ROWS = 2,
  GHOSTTY_TERMINAL_DATA_TITLE = 12,
  GHOSTTY_TERMINAL_DATA_PWD = 13,
} GhosttyTerminalData;

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;

struct MockTerminal {
  uint16_t cols;
  uint16_t rows;
  size_t max_scrollback;
  char *buffer;
  size_t len;
  size_t cap;
  char title[256];
  char pwd[256];
};

struct MockFormatter {
  GhosttyTerminal terminal;
  GhosttyFormatterTerminalOptions options;
};

static void ensure_capacity(struct MockTerminal *terminal, size_t extra) {
  size_t need = terminal->len + extra + 1;
  if (need <= terminal->cap) {
    return;
  }
  size_t next = terminal->cap == 0 ? 256 : terminal->cap;
  while (next < need) {
    next *= 2;
  }
  char *next_buffer = (char *)realloc(terminal->buffer, next);
  if (next_buffer == NULL) {
    return;
  }
  terminal->buffer = next_buffer;
  terminal->cap = next;
}

static void append_char(struct MockTerminal *terminal, char ch) {
  ensure_capacity(terminal, 1);
  if (terminal->buffer == NULL) {
    return;
  }
  terminal->buffer[terminal->len++] = ch;
  terminal->buffer[terminal->len] = '\0';
}

static void append_string(struct MockTerminal *terminal, const char *str) {
  size_t len = strlen(str);
  ensure_capacity(terminal, len);
  if (terminal->buffer == NULL) {
    return;
  }
  memcpy(terminal->buffer + terminal->len, str, len);
  terminal->len += len;
  terminal->buffer[terminal->len] = '\0';
}

static void parse_osc_title(struct MockTerminal *terminal, const uint8_t *data, size_t len, size_t *index) {
  size_t i = *index + 2;
  char title[256];
  size_t out = 0;
  if (i + 1 < len && data[i] == '0' && data[i + 1] == ';') {
    i += 2;
  }
  while (i < len && data[i] != 0x07 && out + 1 < sizeof(title)) {
    title[out++] = (char)data[i++];
  }
  title[out] = '\0';
  strncpy(terminal->title, title, sizeof(terminal->title) - 1);
  terminal->title[sizeof(terminal->title) - 1] = '\0';
  *index = i;
}

static void parse_vt(struct MockTerminal *terminal, const uint8_t *data, size_t len) {
  for (size_t i = 0; i < len; i++) {
    uint8_t ch = data[i];
    if (ch == 0x1b && i + 1 < len) {
      if (data[i + 1] == ']') {
        parse_osc_title(terminal, data, len, &i);
        continue;
      }
      if (data[i + 1] == '[') {
        i += 2;
        while (i < len) {
          uint8_t c = data[i];
          if (c >= 0x40 && c <= 0x7e) {
            break;
          }
          i += 1;
        }
        continue;
      }
      continue;
    }
    append_char(terminal, (char)ch);
  }
}

static uint8_t *format_plain_alloc(const char *src, bool trim, size_t *out_len) {
  size_t len = strlen(src);
  uint8_t *buffer = (uint8_t *)malloc(len == 0 ? 1 : len);
  if (buffer == NULL) {
    *out_len = 0;
    return NULL;
  }
  size_t out = 0;
  for (size_t i = 0; i < len; i++) {
    if (src[i] == '\r') {
      if (i + 1 < len && src[i + 1] == '\n') {
        i += 1;
      }
      buffer[out++] = '\n';
      continue;
    }
    buffer[out++] = (uint8_t)src[i];
  }
  if (trim) {
    while (out > 0 && buffer[out - 1] == '\n') {
      out -= 1;
    }
  }
  *out_len = out;
  return buffer;
}

GhosttyResult ghostty_terminal_new(const void *allocator, GhosttyTerminal *terminal, GhosttyTerminalOptions options) {
  (void)allocator;
  struct MockTerminal *value = (struct MockTerminal *)calloc(1, sizeof(struct MockTerminal));
  if (value == NULL) {
    return GHOSTTY_OUT_OF_MEMORY;
  }
  value->cols = options.cols;
  value->rows = options.rows;
  value->max_scrollback = options.max_scrollback;
  value->pwd[0] = '\0';
  *terminal = value;
  return GHOSTTY_SUCCESS;
}

void ghostty_terminal_free(GhosttyTerminal terminal) {
  if (terminal == NULL) {
    return;
  }
  free(terminal->buffer);
  free(terminal);
}

void ghostty_terminal_reset(GhosttyTerminal terminal) {
  if (terminal == NULL) {
    return;
  }
  terminal->len = 0;
  if (terminal->buffer != NULL) {
    terminal->buffer[0] = '\0';
  }
  terminal->title[0] = '\0';
}

GhosttyResult ghostty_terminal_resize(
    GhosttyTerminal terminal,
    uint16_t cols,
    uint16_t rows,
    uint32_t cell_width_px,
    uint32_t cell_height_px
) {
  (void)cell_width_px;
  (void)cell_height_px;
  if (terminal == NULL) {
    return GHOSTTY_INVALID_VALUE;
  }
  terminal->cols = cols;
  terminal->rows = rows;
  return GHOSTTY_SUCCESS;
}

void ghostty_terminal_vt_write(GhosttyTerminal terminal, const uint8_t *data, size_t len) {
  if (terminal == NULL || data == NULL) {
    return;
  }
  parse_vt(terminal, data, len);
}

GhosttyResult ghostty_terminal_get(GhosttyTerminal terminal, int data, void *out) {
  if (terminal == NULL || out == NULL) {
    return GHOSTTY_INVALID_VALUE;
  }
  switch (data) {
    case GHOSTTY_TERMINAL_DATA_COLS:
      *(uint16_t *)out = terminal->cols;
      return GHOSTTY_SUCCESS;
    case GHOSTTY_TERMINAL_DATA_ROWS:
      *(uint16_t *)out = terminal->rows;
      return GHOSTTY_SUCCESS;
    case GHOSTTY_TERMINAL_DATA_TITLE: {
      GhosttyString *str = (GhosttyString *)out;
      str->ptr = (const uint8_t *)terminal->title;
      str->len = strlen(terminal->title);
      return GHOSTTY_SUCCESS;
    }
    case GHOSTTY_TERMINAL_DATA_PWD: {
      GhosttyString *str = (GhosttyString *)out;
      str->ptr = (const uint8_t *)terminal->pwd;
      str->len = strlen(terminal->pwd);
      return GHOSTTY_SUCCESS;
    }
    default:
      return GHOSTTY_INVALID_VALUE;
  }
}

GhosttyResult ghostty_formatter_terminal_new(
    const void *allocator,
    GhosttyFormatter *formatter,
    GhosttyTerminal terminal,
    GhosttyFormatterTerminalOptions options
) {
  (void)allocator;
  if (terminal == NULL || formatter == NULL) {
    return GHOSTTY_INVALID_VALUE;
  }
  struct MockFormatter *value = (struct MockFormatter *)calloc(1, sizeof(struct MockFormatter));
  if (value == NULL) {
    return GHOSTTY_OUT_OF_MEMORY;
  }
  value->terminal = terminal;
  value->options = options;
  *formatter = value;
  return GHOSTTY_SUCCESS;
}

GhosttyResult ghostty_formatter_format_alloc(
    GhosttyFormatter formatter,
    const void *allocator,
    uint8_t **out_ptr,
    size_t *out_len
) {
  (void)allocator;
  if (formatter == NULL || out_ptr == NULL || out_len == NULL) {
    return GHOSTTY_INVALID_VALUE;
  }
  const char *plain = formatter->terminal->buffer == NULL ? "" : formatter->terminal->buffer;
  size_t plain_len = 0;
  uint8_t *plain_buffer = format_plain_alloc(plain, formatter->options.trim, &plain_len);
  if (plain_buffer == NULL && plain_len == 0) {
    return GHOSTTY_OUT_OF_MEMORY;
  }
  if (formatter->options.emit == GHOSTTY_FORMATTER_FORMAT_HTML) {
    const char *prefix = "<pre>";
    const char *suffix = "</pre>";
    size_t total = strlen(prefix) + plain_len + strlen(suffix);
    uint8_t *buffer = (uint8_t *)malloc(total == 0 ? 1 : total);
    if (buffer == NULL) {
      free(plain_buffer);
      return GHOSTTY_OUT_OF_MEMORY;
    }
    memcpy(buffer, prefix, strlen(prefix));
    memcpy(buffer + strlen(prefix), plain_buffer, plain_len);
    memcpy(buffer + strlen(prefix) + plain_len, suffix, strlen(suffix));
    *out_ptr = buffer;
    *out_len = total;
    free(plain_buffer);
    return GHOSTTY_SUCCESS;
  }
  *out_ptr = plain_buffer;
  *out_len = plain_len;
  return GHOSTTY_SUCCESS;
}

void ghostty_formatter_free(GhosttyFormatter formatter) {
  free(formatter);
}

void ghostty_free(const void *allocator, uint8_t *ptr, size_t len) {
  (void)allocator;
  (void)len;
  free(ptr);
}

GhosttyResult ghostty_build_info(GhosttyBuildInfo data, void *out) {
  if (out == NULL) {
    return GHOSTTY_INVALID_VALUE;
  }
  switch (data) {
    case GHOSTTY_BUILD_INFO_SIMD:
      *(bool *)out = false;
      return GHOSTTY_SUCCESS;
    case GHOSTTY_BUILD_INFO_KITTY_GRAPHICS:
      *(bool *)out = false;
      return GHOSTTY_SUCCESS;
    case GHOSTTY_BUILD_INFO_TMUX_CONTROL_MODE:
      *(bool *)out = false;
      return GHOSTTY_SUCCESS;
    case GHOSTTY_BUILD_INFO_VERSION_STRING: {
      GhosttyString *str = (GhosttyString *)out;
      static const char version[] = "mock-ghostty-vt";
      str->ptr = (const uint8_t *)version;
      str->len = sizeof(version) - 1;
      return GHOSTTY_SUCCESS;
    }
    default:
      return GHOSTTY_INVALID_VALUE;
  }
}
