#include "fb_renderer.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <iostream>
#include <linux/fb.h>
#include <mutex>
#include <string>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>

// Global terminal mutex (defined in image_renderer.cpp)
extern std::mutex g_terminal_mutex;

// The VT (e.g. "2") the rendered output appears on: inside tmux that is the
// tmux client's tty, otherwise our own controlling terminal. Empty when not
// rendering onto a Linux VT console.
static std::string determineVtName() {
  std::string tty;
  const char *pane = getenv("TMUX_PANE");
  if (pane && *pane) {
    std::string cmd = "tmux display-message -p -t '" + std::string(pane) +
                      "' '#{client_tty}' 2>/dev/null";
    FILE *fp = popen(cmd.c_str(), "r");
    if (fp) {
      char buf[64] = {0};
      if (fscanf(fp, "%63s", buf) == 1) {
        tty = buf;
      }
      pclose(fp);
    }
  } else {
    // No TMUX_PANE (browser may be launched by a wrapper shell that dropped
    // the tmux variables): find the pane our controlling tty belongs to.
    char *own = ttyname(STDIN_FILENO);
    if (own) {
      std::string cmd = "tmux list-panes -a -F '#{pane_id} #{pane_tty}' "
                        "2>/dev/null | grep -F ' " + std::string(own) + "'";
      FILE *fp = popen(cmd.c_str(), "r");
      if (fp) {
        char pane_id[128] = {0};
        char pane_tty[256] = {0};
        if (fscanf(fp, "%127s %255s", pane_id, pane_tty) == 2) {
          std::string cmd2 = "tmux display-message -p -t '" +
                             std::string(pane_id) +
                             "' '#{client_tty}' 2>/dev/null";
          FILE *fp2 = popen(cmd2.c_str(), "r");
          if (fp2) {
            char buf[64] = {0};
            if (fscanf(fp2, "%63s", buf) == 1) {
              tty = buf;
            }
            pclose(fp2);
          }
        }
        pclose(fp);
      }
      if (tty.empty()) {
        tty = own;
      }
    }
  }
  const std::string prefix = "/dev/tty";
  if (tty.rfind(prefix, 0) == 0 && tty.size() > prefix.size()) {
    return tty.substr(prefix.size());
  }
  return "";
}

bool FbRenderer::vtIsActive() {
  static const std::string vt = determineVtName();
  if (vt.empty()) {
    return true; // not on a Linux VT console -> nothing to gate
  }
  FILE *fp = fopen("/sys/class/tty/tty0/active", "r");
  if (!fp) {
    return true; // cannot determine -> assume active
  }
  char cur[16] = {0};
  bool ok = fscanf(fp, "%15s", cur) == 1;
  fclose(fp);
  return ok && cur == std::string("tty") + vt;
}

FbRenderer::FbRenderer(int width, int height, int cell_width, int cell_height,
                       int offset_x, int offset_y)
    : width_(width), height_(height), cell_width_(cell_width),
      cell_height_(cell_height), offset_x_(offset_x), offset_y_(offset_y),
      tiled_rendering_enabled_(false), force_full_render_(false) {

  if (getenv("PEAK_NULL_FB")) {
    fb_fd_ = -1;
    fb_map_ = nullptr;
    std::cerr << "FbRenderer: NULL-FB test mode (no /dev/fb0)" << std::endl;
    return;
  }

  fb_fd_ = open("/dev/fb0", O_RDWR);
  if (fb_fd_ < 0) {
    std::cerr << "Failed to open /dev/fb0: " << strerror(errno) << std::endl;
    throw std::runtime_error("Failed to open /dev/fb0");
  }

  struct fb_fix_screeninfo finfo;
  struct fb_var_screeninfo vinfo;
  if (ioctl(fb_fd_, FBIOGET_FSCREENINFO, &finfo) != 0 ||
      ioctl(fb_fd_, FBIOGET_VSCREENINFO, &vinfo) != 0) {
    std::cerr << "Failed to read framebuffer info: " << strerror(errno)
              << std::endl;
    close(fb_fd_);
    fb_fd_ = -1;
    throw std::runtime_error("Failed to read framebuffer info");
  }

  fb_line_length_ = finfo.line_length;
  fb_bpp_ = vinfo.bits_per_pixel;
  fb_red_offset_ = vinfo.red.offset;
  fb_green_offset_ = vinfo.green.offset;
  fb_blue_offset_ = vinfo.blue.offset;

  fb_len_ = finfo.smem_len;
  if (fb_len_ == 0) {
    fb_len_ = static_cast<size_t>(vinfo.yres_virtual) *
              static_cast<size_t>(fb_line_length_);
  }

  fb_map_ = static_cast<uint8_t *>(
      mmap(nullptr, fb_len_, PROT_READ | PROT_WRITE, MAP_SHARED, fb_fd_, 0));
  if (fb_map_ == MAP_FAILED) {
    std::cerr << "Failed to mmap framebuffer: " << strerror(errno) << std::endl;
    close(fb_fd_);
    fb_fd_ = -1;
    fb_map_ = nullptr;
    throw std::runtime_error("Failed to mmap framebuffer");
  }

  // Fast path: 32bpp XRGB8888 with R@16,G@8,B@0 matches the BGRA8888 page
  // buffer byte order (B,G,R,ignored)
  direct_copy_ = (fb_bpp_ == 32 && fb_red_offset_ == 16 &&
                  fb_green_offset_ == 8 && fb_blue_offset_ == 0);

  std::cerr << "FbRenderer: /dev/fb0 " << vinfo.xres << "x" << vinfo.yres
            << " bpp=" << fb_bpp_ << " line=" << fb_line_length_
            << " direct_copy=" << (direct_copy_ ? "yes" : "no") << std::endl;

  // Black out the viewport area so no stale console content shows while the
  // page loads. The reserved status-bar row is left untouched.
  clear();
}

FbRenderer::~FbRenderer() {
  if (fb_map_) {
    munmap(fb_map_, fb_len_);
    fb_map_ = nullptr;
  }
  if (fb_fd_ >= 0) {
    close(fb_fd_);
    fb_fd_ = -1;
  }
}

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

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

  // Never draw onto the screen of a VT that is not the one we run on.
  if (!vtIsActive()) {
    return;
  }

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

  const unsigned char *src_buffer = static_cast<const unsigned char *>(buffer);

  // Full redraw unless tiled rendering is enabled AND we have explicit dirty
  // rects from CEF
  if (force_full_render_ || !tiled_rendering_enabled_ || dirtyRects.empty()) {
    force_full_render_ = false;
    blit(src_buffer, width, height, 0, 0, std::min(width, width_),
         std::min(height, height_));
    return;
  }

  for (const auto &rect : dirtyRects) {
    int x = std::max(0, rect.x);
    int y = std::max(0, rect.y);
    int w = std::min(rect.width, width_ - x);
    int h = std::min(rect.height, height_ - y);
    if (w <= 0 || h <= 0) {
      continue;
    }
    blit(src_buffer, width, height, x, y, w, h);
  }
}

void FbRenderer::clear() {
  if (!fb_map_) {
    return;
  }

  // Never draw onto the screen of a VT that is not the one we run on.
  if (!vtIsActive()) {
    return;
  }

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

  const size_t row_bytes = static_cast<size_t>(fb_line_length_);
  const int fb_w = static_cast<int>(fb_line_length_ / 4);
  const int fb_h = static_cast<int>(fb_len_ / row_bytes);

  int x0 = offset_x_;
  int x1 = std::min(offset_x_ + width_, fb_w);
  int y0 = offset_y_;
  int y1 = std::min(offset_y_ + height_, fb_h);
  if (x1 <= x0 || y1 <= y0) {
    return;
  }

  const size_t clear_bytes = static_cast<size_t>(x1 - x0) * 4;
  for (int y = y0; y < y1; y++) {
    memset(fb_map_ + static_cast<size_t>(y) * row_bytes +
               static_cast<size_t>(x0) * 4,
           0, clear_bytes);
  }
}

void FbRenderer::blit(const unsigned char *src, int src_w, int src_h, int dx,
                      int dy, int w, int h) {
  if (w <= 0 || h <= 0 || dx < 0 || dy < 0) {
    return;
  }

  const size_t row_bytes = static_cast<size_t>(fb_line_length_);
  const int fb_w = static_cast<int>(fb_line_length_ / 4);
  const int fb_h = static_cast<int>(fb_len_ / row_bytes);

  // Destination rect in fb coordinates (view coords + pane offset)
  int x0 = offset_x_ + dx;
  int y0 = offset_y_ + dy;
  int x1 = x0 + w;
  int y1 = y0 + h;

  // Clip to the pane bounds so neighbouring tmux panes are never touched
  x1 = std::min(x1, std::min(offset_x_ + width_, fb_w));
  y1 = std::min(y1, std::min(offset_y_ + height_, fb_h));
  x0 = std::max(x0, offset_x_);
  y0 = std::max(y0, offset_y_);
  if (x1 <= x0 || y1 <= y0) {
    return;
  }

  // Clip against the source buffer (view is width_/height_ pixels, but the
  // page bitmap may be larger or smaller while a resize is in flight)
  int src_x = dx + (x0 - (offset_x_ + dx));
  int src_y = dy + (y0 - (offset_y_ + dy));
  int dst_w = x1 - x0;
  int dst_h = y1 - y0;
  if (src_x + dst_w > src_w) {
    dst_w = src_w - src_x;
  }
  if (src_y + dst_h > src_h) {
    dst_h = src_h - src_y;
  }
  if (dst_w <= 0 || dst_h <= 0) {
    return;
  }

  const size_t src_row_bytes = static_cast<size_t>(src_w) * 4;

  for (int y = 0; y < dst_h; y++) {
    const uint8_t *src_row =
        src + static_cast<size_t>(src_y + y) * src_row_bytes +
        static_cast<size_t>(src_x) * 4;
    uint8_t *dst_row = fb_map_ + static_cast<size_t>(y0 + y) * row_bytes +
                       static_cast<size_t>(x0) * 4;

    if (direct_copy_) {
      memcpy(dst_row, src_row, static_cast<size_t>(dst_w) * 4);
    } else {
      // Generic conversion using the actual channel offsets
      for (int x = 0; x < dst_w; x++) {
        uint32_t b = src_row[x * 4 + 0];
        uint32_t g = src_row[x * 4 + 1];
        uint32_t r = src_row[x * 4 + 2];
        uint32_t a = src_row[x * 4 + 3];
        uint32_t pixel = 0;
        if (fb_red_offset_ < 32) {
          pixel |= (r & 0xFF) << fb_red_offset_;
        }
        if (fb_green_offset_ < 32) {
          pixel |= (g & 0xFF) << fb_green_offset_;
        }
        if (fb_blue_offset_ < 32) {
          pixel |= (b & 0xFF) << fb_blue_offset_;
        }
        // Little-endian pixel storage
        dst_row[x * 4 + 0] = (pixel >> 0) & 0xFF;
        dst_row[x * 4 + 1] = (pixel >> 8) & 0xFF;
        dst_row[x * 4 + 2] = (pixel >> 16) & 0xFF;
        dst_row[x * 4 + 3] = (pixel >> 24) & 0xFF;
      }
    }
  }
}
