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

test("Copy shortcuts with no selection send nothing to bash or cat", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Terminal copy shortcuts", messages: ["Start"] });
  const read = (file: string) => readFile(`${project}/${file}`, "utf8").catch(() => "");
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("export PS1='prompt$ '; echo ready > shell-ready\n");
    return read("shell-ready");
  }, { timeout: 30_000 }).toBe("ready\n");
  await terminal.focus();
  await browser.keyboard.type("clear; echo clean > clean-ready\n");
  await expect.poll(() => read("clean-ready")).toBe("clean\n");
  await browser.keyboard.press("Control+Shift+C");
  await browser.keyboard.press("Control+Insert");
  await app.screenshot("bash-copy-shortcuts-no-selection");
  await browser.keyboard.press("Control+C");
  await browser.keyboard.type("echo ready > cat-ready; cat -v | tee received\n");
  await expect.poll(() => read("cat-ready")).toBe("ready\n");
  await terminal.focus();
  await browser.keyboard.press("Control+Shift+C");
  await browser.keyboard.press("Control+Insert");
  await browser.keyboard.type("END\n");
  await expect.poll(() => read("received")).toContain("END");
  await app.screenshot("cat-copy-shortcuts-no-selection");
  await browser.keyboard.press("Control+C");
  await browser.keyboard.type("echo done > cat-done\n");
  await expect.poll(() => read("cat-done")).toBe("done\n");
  await browser.keyboard.type("echo started > sleep-started; sleep 30; echo NOT-INTERRUPTED\n");
  await expect.poll(() => read("sleep-started")).toBe("started\n");
  await terminal.focus();
  await browser.keyboard.press("Control+C");
  await browser.keyboard.type("echo exit=$? | tee interrupt-result\n");
  await expect.poll(() => read("interrupt-result")).toContain("exit=130");
  await app.screenshot("plain-control-c-still-interrupts");
  expect(await read("received")).toBe("END\n");
});
