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

function tar(mixed: boolean) {
  const bytes = new Uint8Array(mixed ? 3072 : 2048);
  const encoder = new TextEncoder();
  function member(offset: number, name: string, text: string, type: string) {
    const put = (at: number, value: string) => bytes.set(encoder.encode(value), offset + at);
    put(0, name); put(100, "0000644\0"); put(108, "0000000\0");
    put(116, "0000000\0"); put(124, text.length.toString(8).padStart(11, "0") + "\0");
    put(136, "00000000000\0"); put(148, "        "); put(156, type);
    put(257, "ustar\0"); put(263, "00");
    const checksum = bytes.slice(offset, offset + 512).reduce((a, b) => a + b, 0);
    put(148, checksum.toString(8).padStart(6, "0") + "\0 "); put(512, text);
  }
  if (mixed) member(0, "regular.txt", "regular", "0");
  member(mixed ? 1024 : 0, "hello.txt", "hello", "7");
  return bytes;
}

test("Contiguous TAR members appear and open as files", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("tar-demo", { "proof.tar": tar(false), "proof-mixed.tar": tar(true) });
  const thread = await t3.thread({ project, title: "Inspect TAR files", model: "default", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 900 });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByRole("button", "Files F", { exact: true }).tap();
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  const results: boolean[] = [];
  for (const name of ["proof-mixed.tar", "proof.tar"]) {
    await screen.getByRole("treeitem", name, { exact: true }).tap();
    await browser.locator('text=/Archive contents|This archive has no readable entries/').waitFor();
    await app.screenshot(name + "-listing");
    const entry = screen.getByRole("button", /hello.txt/);
    const visible = await entry.isVisible();
    results.push(visible);
    if (visible) {
      await entry.tap();
      await screen.getByText("hello", { exact: true }).waitFor();
      await app.screenshot(name + "-text");
    }
  }
  expect(results).toEqual([true, true]);
});
