/// <reference lib="dom" />
import { DEFAULT_TERMINAL_ID, TERMINAL_WRITE_MAX_LENGTH, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";

import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const PROBE = String.raw`import { writeFileSync } from "node:fs";
process.stdin.on("data", (chunk) => {
  if (chunk.toString().trim() === "status") {
    writeFileSync(new URL("ready", import.meta.url), "ready");
  }
});
process.on("SIGINT", () => {
  process.stdout.write("\r\nStartup interrupted\r\n", () => {
    writeFileSync(new URL("interrupted", import.meta.url), "Startup interrupted");
  });
});
process.stdout.write("Continue startup? [y/n] ", () => {
  writeFileSync(new URL("prompt", import.meta.url), "Continue startup?");
});
`;

test(
  "Ctrl+C interrupts a terminal startup prompt with a long paste pending",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const cwd = await t3.project("demo", { "startup.mjs": PROBE });
    const thread = await t3.thread({ project: cwd, title: "Startup prompt", messages: ["hello"] });
    const withFs = <A, E>(use: (fs: FileSystem.FileSystem) => Effect.Effect<A, E>) =>
      runPromise(Effect.flatMap(FileSystem.FileSystem, use));
    const read = (file: string) =>
      withFs((fs) => fs.readFileString(`${cwd}/${file}`).pipe(Effect.orElseSucceed(() => "")));
    const shell = `${cwd}/startup-shell`;
    await withFs((fs) =>
      fs
        .writeFileString(
          shell,
          `#!/bin/sh\nstty icanon isig -echo\nexec '${process.execPath}' '${cwd}/startup.mjs'\n`,
        )
        .pipe(Effect.andThen(fs.chmod(shell, 0o755))),
    );
    await runPromise(
      rpcClient(T3_HOME, app.baseUrl ?? "").pipe(
        Effect.flatMap((client) =>
          client["terminal.open"]({
            threadId: ThreadId.make(thread.threadId),
            terminalId: DEFAULT_TERMINAL_ID,
            cwd,
            env: { T3CODE_TERMINAL_SHELL: shell },
          }),
        ),
        Effect.scoped,
      ),
    );
    await browser.addInitScript(() => {
      const send = WebSocket.prototype.send;
      WebSocket.prototype.send = function (data) {
        send.call(this, data);
        if (
          typeof data === "string" &&
          data.includes('"terminal.write"') &&
          data.includes('"plainWrite":"start"')
        ) {
          document.documentElement.dataset.terminalPasteStarted = "true";
        }
      };
    });
    await t3.open(thread);
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    const terminal = screen.getByLabel("Terminal input");
    await terminal.focus();
    await expect.poll(() => read("prompt")).toBe("Continue startup?");
    await expect
      .poll(async () => {
        if (await read("ready")) return "ready";
        await browser.keyboard.type("status");
        await browser.keyboard.press("Enter");
        return read("ready");
      })
      .toBe("ready");

    await browser.evaluate(
      (text) => {
        const input = document.querySelector('[aria-label="Terminal input"]');
        if (!input) throw new Error("No terminal input");
        const clipboardData = new DataTransfer();
        clipboardData.setData("text/plain", text);
        input.dispatchEvent(
          new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }),
        );
        return null;
      },
      "x".repeat(TERMINAL_WRITE_MAX_LENGTH + 1),
    );
    await browser
      .locator('html[data-terminal-paste-started="true"]')
      .waitFor({ state: "attached" });
    await browser.keyboard.press("Control+c");

    // The canvas has no DOM text: select all and read what the terminal's copy hands over.
    const terminalText = async () => {
      await browser.evaluate(() => {
        delete document.body.dataset.terminalCopy;
        window.addEventListener(
          "copy",
          (event) => {
            document.body.dataset.terminalCopy = event.clipboardData?.getData("text/plain") ?? "";
          },
          { once: true },
        );
        return null;
      });
      await terminal.focus();
      await browser.keyboard.press("Control+Shift+A");
      await browser.keyboard.press("Control+Shift+C");
      return browser.evaluate(() => document.body.dataset.terminalCopy ?? "");
    };

    try {
      await expect.poll(() => read("interrupted")).toBe("Startup interrupted");
      await expect.poll(terminalText).toContain("Startup interrupted");
      // Cancelling the paste is what the user asked for, not a write failure.
      expect(await terminalText()).not.toContain("Failed to write");
    } finally {
      await app.screenshot("terminal-after-pressing-ctrl-c");
    }
  },
);
