/// <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 { appendFileSync, writeFileSync } from "node:fs";
process.stdin.on("data", (chunk) => {
  appendFileSync(new URL("received", import.meta.url), JSON.stringify(chunk.toString()) + "\n");
  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) + "\n" + "CANCELLED_TAIL",
    );
    await browser
      .locator('html[data-terminal-paste-started="true"]')
      .waitFor({ state: "attached" });
    await browser.keyboard.press("Enter");
    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 ?? "");
    };

    // Record the immediate result without stopping the 65-second observation on base.
    await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 2000)); return null; });
    const immediate = await read("interrupted");
    await app.screenshot("newline-paste-enter-ctrl-c-immediate");
    for (let i = 0; i < 5; i++) await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 13000)); return null; });
    const received = await read("received");
    const text = await terminalText();
    await terminal.focus();
    await browser.keyboard.press("ArrowRight");
    await app.screenshot("newline-paste-enter-ctrl-c-after-deadline");
    expect(immediate).toBe("Startup interrupted");
    expect(text).toContain("Startup interrupted");
    expect(text).not.toContain("Failed to write");
    expect(received).not.toContain("x");
    expect(received).not.toContain("CANCELLED_TAIL");
    expect(received.split("\n").filter(Boolean).every(line => JSON.parse(line) === "status\n")).toBe(true);
  },
);
