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

function archive(signed: boolean) {
  const bytes = Buffer.alloc(2048);
  const put = (offset: number, value: string) => bytes.write(value, offset, "utf8");
  put(0, "café.txt");
  put(100, "0000644\0");
  put(108, "0000000\0");
  put(116, "0000000\0");
  put(124, "00000000005\0");
  put(136, "00000000000\0");
  put(148, "        ");
  put(156, "0");
  put(257, "ustar\0");
  put(263, "00");
  let sum = 0;
  for (const byte of bytes.subarray(0, 512)) sum += signed && byte > 127 ? byte - 256 : byte;
  put(148, `${sum.toString(8).padStart(6, "0")}\0 `);
  put(512, "hello");
  return bytes;
}

test("Signed-byte TAR checksums allow listing and previewing café.txt", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("archive-demo", { "signed.tar": archive(true), "unsigned.tar": archive(false), "warmup.txt": "Preview ready" });
  const startThread = () => t3.thread({ project, title: "Inspect TAR archives", messages: ["Start"] });
  const thread = await startThread().catch((error) => {
    if (!String(error).includes("Advertised models: default")) throw error;
    return startThread();
  });
  await t3.open(thread);
  await screen.getByRole("textbox", "Message Inspect TAR archives", { exact: true }).waitFor({ state: "visible" });
  // Warm the source viewer before opening an archive member: cold Vite optimization reloads the page.
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("warmup.txt");
  await screen.getByRole("option", "warmup.txt", { exact: false }).tap();
  await screen.getByText("Preview ready", { exact: true }).waitFor({ state: "visible", timeout: 120_000 });
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await screen.getByRole("treeitem", "unsigned.tar").tap();
  await screen.getByRole("button", "café.txt", { exact: true }).waitFor({ state: "visible", timeout: 120_000 });
  await app.screenshot("unsigned-control");
  await screen.getByRole("treeitem", "signed.tar").tap();
  await browser.locator('button:has-text("café.txt"), :text-is("The TAR header is damaged.")').waitFor({ state: "visible", timeout: 120_000 });
  await app.screenshot("signed-archive");
  await expect(screen.getByRole("button", "café.txt", { exact: true })).toBeVisible();
  await screen.getByRole("button", "café.txt", { exact: true }).tap();
  await expect(screen.getByText("hello", { exact: true })).toBeVisible();
  await app.screenshot("member-content");
});
