/// <reference lib="dom" />
import { readFile, writeFile, watch } from "node:fs/promises";
import { expect } from "e2e";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Copying an ignored UTF-8 file preserves its BOM byte for byte", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("hello");
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git("remote", "add", "origin", "https://github.com/octocat/Hello-World.git");
  await git("fetch", "origin", "master");
  await git("reset", "--hard", "FETCH_HEAD");
  await writeFile(`${project}/.git/info/exclude`, ".env\nverify.py\nverified\n");
  const original = Buffer.from("efbbbf464f4f3d6261720a", "hex");
  await writeFile(`${project}/.env`, original);
  const destination = `${project}/../copied-hello`;

  const thread = await t3.thread({ project, title: "Ignored file copy — UTF-8 BOM", messages: ["Check ignored file copy"] });
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const pairing = screen.getByRole("dialog");
    await pairing.getByPlaceholder("backend.example.com").fill(host);
    await pairing.getByPlaceholder("PAIRCODE").fill(token);
    await pairing.getByRole("button", "Add environment").tap();
    await screen.getByText("Backend added", { exact: true }).waitFor();
    await t3.open(thread);
    await screen.getByRole("button", "New thread in hello", { exact: true }).first().tap();
    const details = screen.getByRole("button", "Toggle thread details panel", { exact: true });
    if ((await details.getAttribute("aria-pressed")) !== "true") await details.tap();
    await browser.locator('[aria-label^="Run context:"]').last().tap();
    await screen.getByText("Add to another machine", { exact: true }).tap();
    await screen.getByRole("menuitem", "Scenario", { exact: true }).tap();
    const dialog = screen.getByRole("dialog", "Add to another machine");
    await dialog.getByText(".env", { exact: true }).waitFor();
    await dialog.getByRole("textbox").fill(destination);
    await dialog.getByRole("button", "HTTPS", { exact: true }).tap();
    const copied = (async () => {
      for await (const event of watch(`${project}/..`, { recursive: true, signal: AbortSignal.timeout(120_000) })) {
        if (event.filename === "copied-hello/.env") {
          try { if ((await readFile(`${destination}/.env`)).length > 0) return; } catch {}
        }
      }
    })();
    await dialog.getByRole("button", /^Clone to /).tap();
    await dialog.waitFor({ state: "detached", timeout: 120_000 });
    await copied;
  await writeFile(`${project}/verify.py`, `from pathlib import Path\ns = Path('.env').read_bytes()\nd = Path('../copied-hello/.env').read_bytes()\nprint('SOURCE .env:     ', len(s), 'bytes', s.hex())\nprint('DESTINATION .env:', len(d), 'bytes', d.hex())\nprint('BYTE-FOR-BYTE:', 'PRESERVED' if s == d else 'MISMATCH - UTF-8 BOM LOST')\nPath('verified').write_text('done')\n`);
    await t3.open(thread);
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    const terminal = screen.getByLabel("Terminal input");
    await terminal.focus();
    await browser.keyboard.type("export PS1='$ '; clear; python3 verify.py");
    await browser.keyboard.press("Enter");
    // Wait for the terminal command to complete without asserting anything except the copied bytes.
    for (let i = 0; i < 100; i++) {
      try { await readFile(`${project}/verified`); break; } catch { await new Promise(r => setTimeout(r, 100)); }
    }
    await browser.evaluate(() => {
      document.querySelectorAll<HTMLElement>('[data-slot="toast-close"]').forEach(button => button.click());
      return null;
    });
    await app.screenshot("ignored-file-byte-comparison");
    expect((await readFile(`${destination}/.env`)).toString("hex")).toBe(original.toString("hex"));
  } finally { await server.stop(); }
});
