#include "terminal_detector.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <iostream>
#include <linux/fb.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>

TerminalInfo TerminalDetector::detect() {
  TerminalInfo info = {0};

  info.in_tmux = isInTmux();
  info.fb_offset_x = 0;
  info.fb_offset_y = 0;

  info.supports_sixel = checkSixelSupport();
  info.supports_kitty = checkKittySupport();

  bool have_fb = checkFramebufferSupport();

  // The framebuffer console is only ours to draw on when the controlling
  // terminal really is the Linux VT: directly (ttyN) or through a tmux
  // client that itself lives on the VT. Over SSH/pts the framebuffer belongs
  // to the local console - the browser output must go to the terminal
  // (sixel) instead, otherwise nothing would be visible remotely.
  bool client_on_vt = info.in_tmux && have_fb && checkTmuxClientIsVT();
  bool on_vt = isOnLinuxVT() || client_on_vt;

  // tmux on a Linux VT: tmux may advertise sixel/kitty support of its own
  // even though the framebuffer console cannot draw those protocols (the DA1
  // response is unreliable here). The outer terminal is a plain fb console,
  // so render directly into /dev/fb0 scoped to the current pane instead.
  if (client_on_vt) {
    info.supports_sixel = false;
    info.supports_kitty = false;
  }

  info.supports_framebuffer = have_fb && on_vt && !info.supports_sixel &&
                              !info.supports_kitty;

  if (info.supports_framebuffer) {
    // Plain framebuffer console: the page bitmap is blitted 1:1 onto /dev/fb0.
    // Inside tmux only the current pane's pixel area is owned by us, so the
    // geometry is that of the pane plus its offset within /dev/fb0.
    queryFramebufferGeometry(info.width, info.height, info.cell_width,
                             info.cell_height, info.fb_offset_x,
                             info.fb_offset_y);
  } else if (info.supports_sixel || info.supports_kitty) {
    querySixelGeometry(info.width, info.height);

    int cols, rows;
    getTerminalSize(cols, rows);

    if (cols > 0 && rows > 0 && info.width > 0 && info.height > 0) {
      info.cell_width = info.width / cols;
      info.cell_height = info.height / rows;

      // Reserve one row to prevent scrolling after sixel output
      // This prevents the blank line issue in Windows Terminal and others
      info.height = info.height - info.cell_height;
    } else {
      info.cell_width = 8;
      info.cell_height = 16;
      info.width = cols * info.cell_width;
      info.height = rows * info.cell_height;
    }
  }

  // No backend detected but we are on a TTY (SSH): give the sixel fallback in
  // main() a usable cell-based geometry instead of leaving width/height at 0.
  if (info.width <= 0 || info.height <= 0) {
    int cols = 0, rows = 0;
    getTerminalSize(cols, rows);
    info.cell_width = 10;
    info.cell_height = 20;
    if (cols <= 0)
      cols = 80;
    if (rows <= 0)
      rows = 24;
    info.width = cols * info.cell_width;
    info.height = rows * info.cell_height;
  }

  return info;
}

bool TerminalDetector::isInTmux() {
  if (getenv("TMUX")) {
    return true;
  }
  // Fallback: the process may run inside a tmux pane even when the TMUX
  // variables were dropped by a wrapper/login shell. Check whether tmux owns
  // our controlling terminal.
  char *own = ttyname(STDIN_FILENO);
  if (!own) {
    return false;
  }
  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) {
    return false;
  }
  char line[256] = {0};
  bool found = fgets(line, sizeof(line), fp) != nullptr;
  pclose(fp);
  return found;
}

bool TerminalDetector::checkSixelSupport() {
  // Check if stdin is actually a terminal
  if (!isatty(STDIN_FILENO)) {
    return false;
  }

  // Check TERM environment variable for known sixel-capable terminals
  const char *term = getenv("TERM");
  if (term) {
    std::string term_str(term);
    // yaft supports sixel but doesn't report it via DA1
    if (term_str.find("yaft") == 0) {
      return true;
    }
  }

  // Try to query Sixel support via device attributes
  struct termios old_tio, new_tio;
  if (tcgetattr(STDIN_FILENO, &old_tio) != 0) {
    return false;
  }

  new_tio = old_tio;
  new_tio.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &new_tio);

  // Query device attributes (DA1)
  printf("\033[c");
  fflush(stdout);

  char response[128] = {0};
  fd_set fds;
  struct timeval tv;
  FD_ZERO(&fds);
  FD_SET(STDIN_FILENO, &fds);
  tv.tv_sec = 0;
  tv.tv_usec = 200000; // 200ms timeout

  bool supported = false;
  ssize_t got = 0;
  while (select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) > 0) {
    ssize_t n = read(STDIN_FILENO, &response[got], sizeof(response) - got - 1);
    if (n < 0) { break; }
    got += n;
    if (got > 0) {
      // Check for Sixel support in device attributes
      // DA1 response with ";4;" or ";4c" indicates Sixel support
      supported =
          (strstr(response, ";4;") != NULL || strstr(response, ";4c") != NULL);
    }
  }

  tcsetattr(STDIN_FILENO, TCSANOW, &old_tio);

  // Clear any remaining input
  tcflush(STDIN_FILENO, TCIFLUSH);

  return supported;
}

bool TerminalDetector::checkKittySupport() {
  // Check if stdin is actually a terminal
  if (!isatty(STDIN_FILENO)) {
    return false;
  }

  // Check TERM environment variable for known kitty-capable terminals
  const char *term = getenv("TERM");
  if (term) {
    std::string term_str(term);
    // Known terminals that support kitty graphics protocol
    if (term_str.find("kitty") != std::string::npos ||
        term_str.find("xterm-kitty") != std::string::npos) {
      return true;
    }
  }

  // Check TERM_PROGRAM for ghostty and wezterm
  const char *term_program = getenv("TERM_PROGRAM");
  if (term_program) {
    std::string program(term_program);
    if (program.find("ghostty") != std::string::npos ||
        program.find("WezTerm") != std::string::npos) {
      return true;
    }
  }

  // Try to query kitty graphics protocol support
  struct termios old_tio, new_tio;
  if (tcgetattr(STDIN_FILENO, &old_tio) != 0) {
    return false;
  }

  new_tio = old_tio;
  new_tio.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &new_tio);

  // Send a query action with a small 1x1 image to test support
  printf("\033_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\033\\");
  fflush(stdout);

  char response[512] = {0};
  fd_set fds;
  struct timeval tv;
  FD_ZERO(&fds);
  FD_SET(STDIN_FILENO, &fds);
  tv.tv_sec = 0;
  tv.tv_usec = 300000; // 300ms timeout

  bool has_graphics_response = false;
  ssize_t got = 0;

  // Read response with multiple attempts
  for (int attempt = 0; attempt < 3 && !has_graphics_response; attempt++) {
    if (select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) > 0) {
      ssize_t n = read(STDIN_FILENO, response + got, sizeof(response) - got - 1);
      if (n > 0) {
        got += n;
        // Check for kitty graphics protocol response (OK or error)
        if (strstr(response, "\033_Gi=31") != NULL || 
            strstr(response, "_Gi=31") != NULL) {
          has_graphics_response = true;
        }
      }
    }
    // Reset for next read
    FD_ZERO(&fds);
    FD_SET(STDIN_FILENO, &fds);
    tv.tv_sec = 0;
    tv.tv_usec = 100000;
  }

  tcsetattr(STDIN_FILENO, TCSANOW, &old_tio);
  tcflush(STDIN_FILENO, TCIFLUSH);

  return has_graphics_response;
}

bool TerminalDetector::checkFramebufferSupport() {
  // Direct framebuffer access: only useful when NOT running inside a
  // terminal emulator that draws to the fb itself (yaft/fbterm), because
  // its own rendering would fight with our raw blits. Those emulators
  // already report sixel support, so require fb access AND no sixel/kitty.
  int fd = open("/dev/fb0", O_RDWR);
  if (fd >= 0) {
    close(fd);
    return true;
  }
  return false;
}

bool TerminalDetector::isOnLinuxVT() {
  // /dev/ttyN (numeric N) is a kernel virtual terminal; pts sessions (SSH,
  // xterm, tmux switch-servers) are not. Serial consoles (/dev/ttyS*) are
  // excluded by the numeric check as well: they have no framebuffer either.
  char *tty = ttyname(STDIN_FILENO);
  if (!tty || strncmp(tty, "/dev/tty", 8) != 0) {
    return false;
  }
  const char c = tty[8];
  return c >= '0' && c <= '9';
}

bool TerminalDetector::checkTmuxClientIsVT() {
  // tmux runs on a Linux VT (a plain framebuffer console) if the tty of the
  // tmux client is /dev/ttyN. In that case tmux's sixel/kitty claims are
  // lies (fbcon cannot draw them) and direct fb rendering is the only path.
  std::string cmd = "tmux display-message -p";
  const char *tmux_pane = getenv("TMUX_PANE");
  if (tmux_pane && *tmux_pane) {
    cmd += " -t '" + std::string(tmux_pane) + "'";
  }
  cmd += " '#{client_tty}' 2>/dev/null";
  FILE *fp = popen(cmd.c_str(), "r");
  if (!fp) {
    return false;
  }
  char tty[256] = {0};
  bool ok = fscanf(fp, "%255s", tty) == 1;
  pclose(fp);
  return ok && strncmp(tty, "/dev/tty", 8) == 0;
}

void TerminalDetector::queryFramebufferGeometry(int &width, int &height,
                                                int &cell_width,
                                                int &cell_height,
                                                int &fb_offset_x,
                                                int &fb_offset_y) {
  int fd = open("/dev/fb0", O_RDWR);
  if (fd < 0) {
    width = 0;
    height = 0;
    cell_width = 8;
    cell_height = 16;
    fb_offset_x = 0;
    fb_offset_y = 0;
    return;
  }

  struct fb_var_screeninfo vinfo;
  if (ioctl(fd, FBIOGET_VSCREENINFO, &vinfo) != 0 || vinfo.xres <= 0 ||
      vinfo.yres <= 0) {
    close(fd);
    width = 0;
    height = 0;
    cell_width = 8;
    cell_height = 16;
    fb_offset_x = 0;
    fb_offset_y = 0;
    return;
  }
  close(fd);

  int pane_left = 0, pane_top = 0, pane_cols = 0, pane_rows = 0;
  int console_cols = 0, console_rows = 0;

  bool in_tmux = getenv("TMUX") != nullptr;
  bool have_tmux = in_tmux && queryTmuxGeometry(pane_left, pane_top, pane_cols,
                                                pane_rows, console_cols,
                                                console_rows);

  if (have_tmux && console_cols > 0 && console_rows > 0) {
    // tmux reports its pane position/size in character cells of the client
    // terminal (here: the framebuffer console). The pane's top-left corner
    // maps 1:1 onto the framebuffer, so the pixel offset and size are
    // pane_cell * (fb_size / client_cells).
    cell_width = vinfo.xres / console_cols;
    cell_height = vinfo.yres / console_rows;
    if (cell_width < 1)
      cell_width = 1;
    if (cell_height < 1)
      cell_height = 1;

    fb_offset_x = pane_left * cell_width;
    fb_offset_y = pane_top * cell_height;
    width = pane_cols * cell_width;
    height = pane_rows * cell_height;
  } else {
    int cols, rows;
    getTerminalSize(cols, rows);
    if (cols > 0 && rows > 0) {
      cell_width = vinfo.xres / cols;
      cell_height = vinfo.yres / rows;
      if (cell_width < 1)
        cell_width = 1;
      if (cell_height < 1)
        cell_height = 1;
    } else {
      cell_width = 10;
      cell_height = 20;
    }

    width = vinfo.xres;
    height = vinfo.yres;
    fb_offset_x = 0;
    fb_offset_y = 0;
  }

  // No status bar: the browser view uses the full pane/framebuffer height.
}

bool TerminalDetector::queryTmuxGeometry(int &pane_left, int &pane_top,
                                         int &pane_width, int &pane_height,
                                         int &client_width, int &client_height) {
  pane_left = pane_top = pane_width = pane_height = 0;
  client_width = client_height = 0;

  std::string target;
  const char *tmux_pane = getenv("TMUX_PANE");
  if (tmux_pane && *tmux_pane) {
    // tmux sets TMUX_PANE for every process it launches inside a pane. This
    // stays correct even when the pane is not the currently focused one.
    target = tmux_pane;
  } else {
    // Fallback: find the pane whose pty matches our controlling terminal.
    FILE *statfp = fopen("/proc/self/stat", "r");
    if (statfp) {
      int pid = 0, tty_nr = 0;
      char state = 0;
      char comm[512] = {0};
      // pid (comm) state ppid pgrp session tty_nr ...
      if (fscanf(statfp, "%d (%511[^)]) %c %*d %*d %*d %d", &pid, comm, &state,
                 &tty_nr) == 4) {
        unsigned major = (static_cast<unsigned>(tty_nr) >> 8) & 0xfff;
        unsigned minor = (static_cast<unsigned>(tty_nr) & 0xff) |
                         ((static_cast<unsigned>(tty_nr) >> 12) & 0xfff00);
        std::string tty;
        if (major == 4) {
          tty = "/dev/tty" + std::to_string(minor);
        } else if (major >= 136 && major <= 143) {
          tty = "/dev/pts/" + std::to_string(minor);
        }
        if (!tty.empty()) {
          std::string cmd =
              "tmux list-panes -a -F "
              "'#{pane_id} #{pane_tty}' 2>/dev/null | grep -F ' " + tty + "'";
          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 &&
                strcmp(pane_tty, tty.c_str()) == 0) {
              target = pane_id;
            }
            pclose(fp);
          }
        }
      }
      fclose(statfp);
    }
    if (target.empty()) {
      return false;
    }
  }

  std::string cmd = "tmux display-message -p -t '" + target +
                    "' '#{pane_left} #{pane_top} #{pane_width} #{pane_height} "
                    "#{client_width} #{client_height}' 2>/dev/null";
  FILE *fp = popen(cmd.c_str(), "r");
  if (!fp) {
    return false;
  }

  bool ok = fscanf(fp, "%d %d %d %d %d %d", &pane_left, &pane_top, &pane_width,
                   &pane_height, &client_width, &client_height) == 6 &&
            pane_width > 0 && pane_height > 0 && client_width > 0 &&
            client_height > 0;
  pclose(fp);
  return ok;
}

void TerminalDetector::querySixelGeometry(int &width, int &height) {
  struct termios old_tio, new_tio;
  tcgetattr(STDIN_FILENO, &old_tio);
  new_tio = old_tio;
  new_tio.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &new_tio);

  // In tmux, get pane size directly
  if (getenv("TMUX")) {
    FILE *fp = popen("tmux display-message -p '#{pane_height} #{pane_width}' 2>/dev/null", "r");
    if (fp) {
      int h = 0, w = 0;
      if (fscanf(fp, "%d %d", &h, &w) == 2 && h > 0 && w > 0) {
        height = h * 20;
        width = w * 10;
      }
      pclose(fp);
    }
    tcsetattr(STDIN_FILENO, TCSANOW, &old_tio);
    return;
  }

  // Method 1: Try Sixel geometry query (works on mlterm, xterm)
  printf("\033[?2;1;0S");
  fflush(stdout);

  char response[128] = {0};
  fd_set fds;
  struct timeval tv;
  FD_ZERO(&fds);
  FD_SET(STDIN_FILENO, &fds);
  tv.tv_sec = 0;
  tv.tv_usec = 100000;

  bool got_response = false;
  ssize_t got = 0;
  while (select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) > 0) {
    ssize_t n = read(STDIN_FILENO, &response[got], sizeof(response) - got - 1);
    if (n < 0) { break; }
    got += n;
    if (got > 0 && sscanf(response, "\033[?2;0;%d;%dS", &width, &height) == 2) {
      if (width > 0 && height > 0) {
        got_response = true;
      }
    }
  }

  // Method 2: Try XTerm window size query (works on Windows Terminal, many
  // others)
  if (!got_response) {
    tcflush(STDIN_FILENO, TCIFLUSH);
    memset(response, 0, sizeof(response));

    printf("\033[14t");
    fflush(stdout);

    FD_ZERO(&fds);
    FD_SET(STDIN_FILENO, &fds);
    tv.tv_sec = 0;
    tv.tv_usec = 100000;

    ssize_t got = 0;
    while (select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) > 0) {
      ssize_t n = read(STDIN_FILENO, &response[got], sizeof(response) - got - 1);
      if (n < 0) { break; }
      got += n;
      if (got > 0) {
        int h = 0, w = 0;
        if (sscanf(response, "\033[4;%d;%dt", &h, &w) == 2) {
          if (w > 0 && h > 0) {
            width = w;
            height = h;
            got_response = true;
          }
        }
      }
    }
  }

  // Method 3: Try ioctl pixel dimensions (if available)
  if (!got_response) {
    struct winsize w;
    if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0) {
      if (w.ws_xpixel > 0 && w.ws_ypixel > 0) {
        width = w.ws_xpixel;
        height = w.ws_ypixel;
        got_response = true;
      }
    }
  }

  // Method 4: CSI 16 t - pixel size of one character cell (xterm and Windows
  // Terminal 1.22+). Multiplying the cell size by the cell count is the most
  // reliable way to size sixel output on terminals whose window size queries
  // are answered in cells rather than pixels.
  if (!got_response) {
    tcflush(STDIN_FILENO, TCIFLUSH);
    memset(response, 0, sizeof(response));

    printf("\033[16t");
    fflush(stdout);

    FD_ZERO(&fds);
    FD_SET(STDIN_FILENO, &fds);
    tv.tv_sec = 0;
    tv.tv_usec = 100000;

    ssize_t got = 0;
    while (select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) > 0) {
      ssize_t n = read(STDIN_FILENO, &response[got], sizeof(response) - got - 1);
      if (n < 0) { break; }
      got += n;
      if (got > 0) {
        int cell_h = 0, cell_w = 0;
        if (sscanf(response, "\033[6;%d;%dt", &cell_h, &cell_w) == 2) {
          if (cell_w > 0 && cell_h > 0) {
            int cols = 0, rows = 0;
            getTerminalSize(cols, rows);
            if (cols > 0 && rows > 0) {
              width = cols * cell_w;
              height = rows * cell_h;
              got_response = true;
            }
          }
        }
      }
    }
  }

  tcsetattr(STDIN_FILENO, TCSANOW, &old_tio);
  tcflush(STDIN_FILENO, TCIFLUSH);

  // Fallback: Use better defaults for modern terminals
  if (!got_response || width <= 0 || height <= 0) {
    int cols, rows;
    getTerminalSize(cols, rows);
    // Modern terminals typically use 10x20 pixel cells (Windows Terminal's
    // sixel renderer exactly - it emulates the VT340 with a fixed 10x20 cell).
    width = cols * 10;
    height = rows * 20;
  }
}

void TerminalDetector::getTerminalSize(int &cols, int &rows) {
  struct winsize w;
  if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0) {
    cols = w.ws_col;
    rows = w.ws_row;
  } else {
    cols = 80;
    rows = 24;
  }
}
