#include "sixel_renderer.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <string>
#include <unistd.h>
#include <sixel.h>

// Global terminal mutex (defined in image_renderer.cpp), shared with the
// framebuffer renderer and any other consumer of the terminal output.
extern std::mutex g_terminal_mutex;

namespace {
constexpr int kDesiredColors = 256; // libsixel palette size (0..256)
constexpr int kStripBaseWidth = 160; // nominal tiled strip width in pixels

// Inside tmux we wrap every sixel DCS in the tmux passthrough envelope
// (ESC P tmux; ... ESC \). tmux then forwards the sixel sequence verbatim to
// the client terminal instead of intercepting it: that avoids the "SIXEL
// IMAGE (WxH)" placeholder tmux otherwise draws when its client does not
// report a pixel size (e.g. over SSH/Windows Terminal). Requires
// `set -ga allow-passthrough on` in tmux.conf.
//
// Verified against tmux 3.7c: tmux swallows ONE ESC right after "tmux;", so
// the envelope is opened as ESC P tmux; ESC (the ESC re-arms the payload's
// own ESC P q introducer) and closed with a single ESC \ after the image.
bool tmuxPassthroughEnabled() {
  static const bool enabled = getenv("TMUX") != nullptr;
  return enabled;
}

void tmuxPassthroughOpen() {
  if (tmuxPassthroughEnabled()) {
    fputs("\x1bPtmux;\x1b", stdout);
  }
}

void tmuxPassthroughClose() {
  if (tmuxPassthroughEnabled()) {
    fputs("\x1b\\", stdout);
  }
}
} // namespace

SixelRenderer::SixelRenderer(int width, int height, int cell_width,
                             int cell_height)
    : width_(width), height_(height), cell_width_(cell_width),
      cell_height_(cell_height), output_(nullptr), tile_w_(width) {

  // Tiled mode splits the width into full-height column strips of roughly
  // kStripBaseWidth pixels (bounded so a huge screen does not produce a huge
  // number of strips). Every strip spans the whole height, so sixel's 6-row
  // band packing always stays aligned.
  const int columns = std::max(1, std::min(8, (width + kStripBaseWidth - 1) /
                                                  kStripBaseWidth));
  tile_w_ = (width + columns - 1) / columns;

  sixel_output_t *out = nullptr;
  if (sixel_output_new(&out, &SixelRenderer::sixelWriteCallback, nullptr,
                       nullptr) != SIXEL_OK ||
      out == nullptr) {
    fprintf(stderr, "peak: failed to create libsixel output\n");
    out = nullptr;
  }
  output_ = out;

  // When running inside tmux we emit through the tmux passthrough envelope
  // (see tmuxPassthroughOpen). That only works if the tmux server has
  // `allow-passthrough on` - enable it best-effort so peak works even in
  // tmux servers started before the option was added to tmux.conf.
  if (tmuxPassthroughEnabled()) {
    FILE *pf = popen("env -u LD_PRELOAD -u TORSOCKS_CONF_FILE "
                     "tmux set -ga allow-passthrough on 2>/dev/null", "r");
    if (pf) {
      pclose(pf);
    }
  }
}

SixelRenderer::~SixelRenderer() {
  if (output_) {
    sixel_output_unref(static_cast<sixel_output_t *>(output_));
    output_ = nullptr;
  }
}

std::mutex &SixelRenderer::getTerminalMutex() { return g_terminal_mutex; }

int SixelRenderer::sixelWriteCallback(char *data, int size, void * /*priv*/) {
  // libsixel streams the generated sixel chunks straight to stdout.
  return fwrite(data, 1, static_cast<size_t>(size), stdout) ==
                 static_cast<size_t>(size)
             ? 0
             : -1;
}

void SixelRenderer::encodeImage(const unsigned char *pixels, int w, int h) {
  if (!output_ || !pixels || w <= 0 || h <= 0) {
    return;
  }

  sixel_dither_t *dither = nullptr;
  if (sixel_dither_new(&dither, kDesiredColors, nullptr) != SIXEL_OK ||
      dither == nullptr) {
    fprintf(stderr, "peak: failed to create libsixel dither\n");
    return;
  }

  // Build the palette from the actual frame (BGRA8888 matches the raw page
  // bitmap byte order peak uses everywhere) and let libsixel emit the sixel
  // image. The `depth` argument is ignored by the encoder.
  sixel_dither_initialize(dither, const_cast<unsigned char *>(pixels), w, h,
                          SIXEL_PIXELFORMAT_BGRA8888, SIXEL_LARGE_AUTO,
                          SIXEL_REP_AUTO, SIXEL_QUALITY_HIGH);
  sixel_encode(const_cast<unsigned char *>(pixels), w, h, 4, dither,
               static_cast<sixel_output_t *>(output_));
  sixel_dither_unref(dither);
}

bool SixelRenderer::isTileDirty(const unsigned char *frame, int x0, int y0,
                                int w, int h) {
  const size_t expected = static_cast<size_t>(width_) * height_ * 4;
  if (last_frame_.size() != expected || frame == nullptr || w <= 0 || h <= 0) {
    return true; // no reference frame yet -> must (re)draw
  }
  const size_t pitch = static_cast<size_t>(width_) * 4;
  for (int y = 0; y < h; y++) {
    const unsigned char *a =
        frame + static_cast<size_t>(y0 + y) * pitch + static_cast<size_t>(x0) * 4;
    const unsigned char *b =
        last_frame_.data() + static_cast<size_t>(y0 + y) * pitch +
        static_cast<size_t>(x0) * 4;
    if (memcmp(a, b, static_cast<size_t>(w) * 4) != 0) {
      return true;
    }
  }
  return false;
}

void SixelRenderer::renderTile(const unsigned char *frame, int x0, int x1) {
  const int tw = x1 - x0;
  if (tw <= 0 || height_ <= 0) {
    return;
  }

  // libsixel needs one contiguous pixel buffer, so copy the strip out of the
  // full frame first (same approach the original brow6el renderer used).
  std::vector<unsigned char> strip(static_cast<size_t>(tw) * height_ * 4);
  const size_t pitch = static_cast<size_t>(width_) * 4;
  for (int y = 0; y < height_; y++) {
    memcpy(strip.data() + static_cast<size_t>(y) * tw * 4,
           frame + static_cast<size_t>(y) * pitch + static_cast<size_t>(x0) * 4,
           static_cast<size_t>(tw) * 4);
  }
  strip.shrink_to_fit();

  // Park the sixel graphics cursor at the strip's top-left corner, then draw.
  printf("\x1b[1;%dH", x0 + 1);
  tmuxPassthroughOpen();
  encodeImage(strip.data(), tw, height_);
  tmuxPassthroughClose();

  // Record the strip so isTileDirty can skip it on the next paint.
  if (last_frame_.size() != static_cast<size_t>(width_) * height_ * 4) {
    last_frame_.assign(static_cast<size_t>(width_) * height_ * 4, 0);
  }
  for (int y = 0; y < height_; y++) {
    memcpy(last_frame_.data() + static_cast<size_t>(y) * pitch +
               static_cast<size_t>(x0) * 4,
           strip.data() + static_cast<size_t>(y) * tw * 4,
           static_cast<size_t>(tw) * 4);
  }
}

void SixelRenderer::renderMonolithic(const unsigned char *frame) {
  if (!frame || width_ <= 0 || height_ <= 0) {
    return;
  }

  const size_t bytes = static_cast<size_t>(width_) * height_ * 4;
  last_frame_.assign(frame, frame + bytes);

  printf("\x1b[H\x1b[?25l"); // home the cursor and hide it during the draw
  tmuxPassthroughOpen();
  encodeImage(frame, width_, height_);
  tmuxPassthroughClose();
  fputs("\x1b[?25h", stdout); // show the cursor again
}

void SixelRenderer::render(const void *buffer, int width, int height,
                           bool hasAlpha,
                           const std::vector<CefRect> &dirtyRects) {
  if (!buffer || width_ <= 0 || height_ <= 0 || width <= 0 || height <= 0) {
    return;
  }

  std::lock_guard<std::mutex> lock(g_terminal_mutex);

  // During a terminal resize CEF may deliver a frame whose size differs from
  // the terminal geometry. Scale it to the rendered size first (nearest
  // neighbour) so the stream always fills exactly the terminal.
  const unsigned char *frame = static_cast<const unsigned char *>(buffer);
  std::vector<unsigned char> scaled;
  if (width != width_ || height != height_) {
    scaled.resize(static_cast<size_t>(width_) * height_ * 4);
    for (int y = 0; y < height_; y++) {
      const int sy = static_cast<int>(static_cast<int64_t>(y) * height / height_);
      const unsigned char *src_row =
          static_cast<const unsigned char *>(buffer) +
          static_cast<size_t>(sy) * width * 4;
      unsigned char *dst_row = scaled.data() + static_cast<size_t>(y) * width_ * 4;
      for (int x = 0; x < width_; x++) {
        const int sx =
            static_cast<int>(static_cast<int64_t>(x) * width / width_);
        memcpy(dst_row + static_cast<size_t>(x) * 4,
               src_row + static_cast<size_t>(sx) * 4, 4);
      }
    }
    frame = scaled.data();
  }

  // Tiled rendering only helps when CEF reports specific dirty regions.
  const bool do_tiles =
      tiled_rendering_enabled_ && !force_full_render_ && !dirtyRects.empty();

  if (!do_tiles) {
    force_full_render_ = false;
    renderMonolithic(frame);
    fflush(stdout);
    return;
  }
  force_full_render_ = false;

  // Map every dirty rect onto the strip grid and note the strips touched.
  const int strips = (width_ + tile_w_ - 1) / tile_w_;
  std::vector<unsigned char> touched(strips, 0);
  for (const auto &rect : dirtyRects) {
    if (rect.width <= 0 || rect.height <= 0) {
      continue;
    }
    int c0 = rect.x / tile_w_;
    int c1 = (rect.x + rect.width - 1) / tile_w_;
    if (c0 < 0)
      c0 = 0;
    if (c1 >= strips)
      c1 = strips - 1;
    for (int c = c0; c <= c1; c++) {
      touched[static_cast<size_t>(c)] = 1;
    }
  }

  printf("\x1b[?25l"); // hide the cursor while strips are (re)drawn
  for (int c = 0; c < strips; c++) {
    if (!touched[c]) {
      continue;
    }
    const int x0 = c * tile_w_;
    const int x1 = std::min(x0 + tile_w_, width_);
    if (isTileDirty(frame, x0, 0, x1 - x0, height_)) {
      renderTile(frame, x0, x1);
    }
  }
  fputs("\x1b[?25h", stdout);
  fflush(stdout);
}

void SixelRenderer::clear() {
  if (width_ <= 0 || height_ <= 0) {
    return;
  }

  std::lock_guard<std::mutex> lock(g_terminal_mutex);

  // Black rectangle: one opaque BGRA frame of zeros.
  std::vector<unsigned char> black(static_cast<size_t>(width_) * height_ * 4, 0);
  renderMonolithic(black.data());
  fflush(stdout);
}