// End-to-end test of peak's SixelRenderer exactly as BrowserClient uses it.
// Feeds synthetic BGRA frames (the same pixel layout CEF provides) and checks
// the sixel DCS stream emitted for monolithic / tiled / clear paths.
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>

#include "sixel_renderer.h"
#include "image_renderer.cpp"
#include "sixel_renderer.cpp"

static std::string captureRun(int (*run)(void *), void *arg, int *count_outs) {
  int saved = dup(STDOUT_FILENO);
  const char *path = "/tmp/opencode/sixelr_out.bin";
  int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
  if (fd < 0) return "";
  dup2(fd, STDOUT_FILENO);
  int rc = run(arg); // run inside redirection
  fflush(stdout);
  (void)rc;
  close(fd); // -> EOF for the reader below
  dup2(saved, STDOUT_FILENO);
  close(saved);
  FILE *f = fopen(path, "rb");
  std::string s;
  char buf[65536];
  size_t n;
  while ((n = fread(buf, 1, sizeof buf, f)) > 0)
    s.append(buf, n);
  fclose(f);
  if (count_outs) *count_outs = 0;
  return s;
}

static std::vector<unsigned char> makeFrame(int w, int h, unsigned char base) {
  std::vector<unsigned char> f((size_t)w * h * 4);
  for (size_t i = 0; i < f.size(); i += 4) {
    f[i + 0] = (unsigned char)(base);
    f[i + 1] = (unsigned char)(base + 40);
    f[i + 2] = (unsigned char)(base + 80);
    f[i + 3] = 255;
  }
  return f;
}

static int count(const std::string &s, const char *needle) {
  int n = 0;
  size_t pos = 0, l = strlen(needle);
  while ((pos = s.find(needle, pos)) != std::string::npos) {
    n++;
    pos += l;
  }
  return n;
}

namespace {

struct MonoArgs {
  SixelRenderer *r;
  const void *buf;
  int w, h;
};
int monoRun(void *v) {
  MonoArgs *a = (MonoArgs *)v;
  a->r->render(a->buf, a->w, a->h, false);
  return 0;
}

struct TileArgs {
  SixelRenderer *r;
  const void *buf;
  int w, h;
  std::vector<CefRect> rects;
};
int tileRun(void *v) {
  TileArgs *a = (TileArgs *)v;
  a->r->render(a->buf, a->w, a->h, false, a->rects);
  return 0;
}

struct ClearArgs {
  SixelRenderer *r;
};
int clearRun(void *v) {
  ((ClearArgs *)v)->r->clear();
  return 0;
}

} // namespace

int main() {
  setvbuf(stdout, NULL, _IONBF, 0);
  int fails = 0;
  const int W = 640, H = 384;

  { // monolithic (default)
    SixelRenderer r(W, H, 8, 16);
    auto f = makeFrame(W, H, 10);
    MonoArgs a{&r, f.data(), W, H};
    std::string out = captureRun(monoRun, &a, nullptr);
    int dcs = count(out, "\x1bPq");
    if (dcs != 1) { printf("FAIL monolithic: expected 1 DCS, got %d\n", dcs); fails++; }
    if (out.find("\x1b[H") == std::string::npos) { printf("FAIL monolithic: no home\n"); fails++; }
    if (out.find("\x1b[?25h") == std::string::npos || out.find("\x1b\\") == std::string::npos) {
      printf("FAIL monolithic: no cursor-show / DCS end\n"); fails++;
    }
    if (count(out, "#0;2;") < 1) { printf("FAIL monolithic: no palette\n"); fails++; }
    printf("ok monolithic bytes=%zu dcs=%d\n", out.size(), dcs);
  }

  { // monolithic at mismatched frame size must scale
    SixelRenderer r(W, H, 8, 16);
    auto f = makeFrame(W * 2, H * 2, 20);
    MonoArgs a{&r, f.data(), W * 2, H * 2};
    std::string out = captureRun(monoRun, &a, nullptr);
    int dcs = count(out, "\x1bPq");
    if (dcs != 1) { printf("FAIL scale: expected 1 DCS, got %d\n", dcs); fails++; }
    printf("ok scale bytes=%zu\n", out.size());
  }

  { // tiled: identical frame -> cache hit emits nothing; changed strip -> 1 DCS
    SixelRenderer r(W, H, 8, 16);
    r.setTiledRenderingEnabled(true); // tiles + full-render priming
    auto f = makeFrame(W, H, 30);
    MonoArgs prime{&r, f.data(), W, H};
    std::string out = captureRun(monoRun, &prime, nullptr); // primes cache (full)
    if (count(out, "\x1bPq") != 1) { printf("FAIL tiled prime\n"); fails++; }

    std::vector<CefRect> rects;
    rects.push_back(CefRect(20, 40, 30, 50)); // touches strip 0 only

    TileArgs same{&r, f.data(), W, H, rects};
    out = captureRun(tileRun, &same, nullptr);
    if (count(out, "\x1bPq") != 0) { printf("FAIL tiled: identical frame re-encoded\n"); fails++; }

    auto f2 = makeFrame(W, H, 31); // only strip 0 differs
    TileArgs chg{&r, f2.data(), W, H, rects};
    out = captureRun(tileRun, &chg, nullptr);
    int dcs = count(out, "\x1bPq");
    if (dcs != 1) { printf("FAIL tiled: expected 1 strip DCS, got %d\n", dcs); fails++; }
    if (out.find("\x1b[1;1H") == std::string::npos) { printf("FAIL tiled: strip not positioned\n"); fails++; }
    printf("ok tiled cache+strip bytes=%zu dcs=%d\n", out.size(), dcs);
  }

  { // tiled: a dirty rect on a *different* strip encodes that strip only
    SixelRenderer r(W, H, 8, 16);
    r.setTiledRenderingEnabled(true); // tiles + full-render priming
    auto f = makeFrame(W, H, 40);
    MonoArgs prime{&r, f.data(), W, H};
    std::string out = captureRun(monoRun, &prime, nullptr);

    std::vector<CefRect> rects;
    rects.push_back(CefRect(400, 100, 40, 60)); // strip 2 (640/160 -> 4 strips)
    auto f2 = makeFrame(W, H, 41);
    TileArgs chg{&r, f2.data(), W, H, rects};
    out = captureRun(tileRun, &chg, nullptr);
    int dcs = count(out, "\x1bPq");
    if (dcs != 1) { printf("FAIL tiled-strip: expected 1 DCS, got %d\n", dcs); fails++; }
    if (out.find("\x1b[1;321H") == std::string::npos) { printf("FAIL tiled-strip: wrong/absent position (%zu)\n", out.size()); fails++; }
    printf("ok tiled-strip dcs=%d\n", dcs);
  }

  { // clear
    SixelRenderer r(W, H, 8, 16);
    ClearArgs a{&r};
    std::string out = captureRun(clearRun, &a, nullptr);
    if (count(out, "\x1bPq") != 1) { printf("FAIL clear: expected 1 DCS\n"); fails++; }
    printf("ok clear bytes=%zu\n", out.size());
  }

  printf(fails ? "\nRESULT: %d FAILURES\n" : "\nRESULT: ALL PASS\n", fails);
  return fails ? 1 : 0;
}