import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

function archive(binary: boolean) {
  const bytes = Buffer.alloc(2048);
  const field = (offset: number, value: string) => bytes.write(value, offset, "ascii");
  field(0, "hello.txt");
  field(100, "0000644\0");
  field(108, "0000000\0");
  field(116, "0000000\0");
  field(124, "00000000003\0");
  if (binary) { bytes.fill(0, 124, 136); bytes[124] = 0x80; bytes[135] = 3; }
  field(136, "00000000000\0");
  bytes.fill(32, 148, 156);
  field(156, "0");
  field(257, "ustar \0");
  let checksum = 0;
  for (const byte of bytes.subarray(0, 512)) checksum += byte;
  field(148, checksum.toString(8).padStart(6, "0") + "\0 ");
  field(512, "hi\n");
  return bytes;
}

test("GNU binary size TAR lists and opens its member", WEB, async ({ t3, app, screen, browser }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("tar-preview", {
    "README.md": "Synthetic GNU TAR preview fixture.\n",
    "sample.tar": archive(true),
    "control.tar": archive(false),
  });
  const thread = await t3.thread({ project, title: "Inspect TAR archive", messages: ["Start"], model: "default" });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "sample.tar").tap();
  await screen.getByRole("button", "Hide file explorer").tap();
  await expect.poll(() => browser.evaluate(() => document.body.textContent?.includes("Archive contents") || document.body.textContent?.includes("This TAR uses an unsupported numeric format."))).toBe(true);
  await app.screenshot("archive-list");
  await expect(screen.getByRole("button", "hello.txt", { exact: true })).toBeVisible();
  await expect(screen.getByRole("table", "Archive entries").getByText("1 KB", { exact: true })).toBeVisible();
  await screen.getByRole("button", "hello.txt", { exact: true }).tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("diffs-container")) {
      const lines = host.shadowRoot?.querySelectorAll("[data-line]");
      if (lines?.length) return [...lines].map((line) => line.textContent).join("\n");
    }
    const member = [...document.querySelectorAll("button")].find((button) => button.textContent === "hello.txt");
    member?.click();
    return null;
  })).toBe("hi\n");
  await app.screenshot("member-content");
});
