import { readFile, watch } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("File editor autosave preserves the UTF-8 BOM", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("bom-demo", { "answer.ts": "\uFEFFexport const answer = 42;\n", "t3.json": "\uFEFF" + JSON.stringify({ scripts: [{ name: "BOM config readable", command: "printf config-readable", icon: "play" }] }) });
  const thread = await t3.thread({ project, title: "BOM preservation", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("button", "Project actions").tap();
  await screen.getByText("BOM config readable", { exact: true }).waitFor();
  await app.screenshot("bom-config-readable");
  await browser.keyboard.press("Escape");
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", /^Files/).tap();
  await screen.getByRole("treeitem", "answer.ts").tap();
  const editor = browser.locator(".file-preview-virtualizer [contenteditable=true][role=textbox]");
  await editor.tap();
  await app.screenshot("opened-bom-file");
  await browser.keyboard.press("Control+End");
  await browser.keyboard.press("ArrowLeft");
  await browser.keyboard.press("ArrowLeft");
  await browser.keyboard.press("Backspace");
  await browser.keyboard.type("3");
  await expect.poll(async () => (await readFile(`${project}/answer.ts`, "utf8")).includes("answer = 43;")).toBe(true);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByRole("textbox", "Terminal input");
  await terminal.press("Control+u");
  const complete = (async () => {
    for await (const event of watch(project)) {
      if (event.filename === ".inspection-complete") break;
    }
  })();
  await browser.keyboard.type("export PS1='$ '; clear; printf 'Saved answer.ts bytes (UTF-8 BOM = ef bb bf):\\n'; od -An -tx1 answer.ts; printf '\\nSaved source:\\n'; cat answer.ts; printf '\\n'; touch .inspection-complete");
  await browser.keyboard.press("Enter");
  await complete;
  await app.screenshot("autosaved-file");
  const bytes = await readFile(`${project}/answer.ts`);
  expect(bytes.subarray(0, 3).toString("hex")).toBe("efbbbf");
});
