/// <reference lib="dom" />
import { writeFile, chmod, readFile } from "node:fs/promises";
import { DEFAULT_TERMINAL_ID, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const LINE = `: ${"x".repeat(4970)}; echo PASTED-COMMAND-RAN`;
test("Enter after a held startup paste submits it once", WEB, async ({t3, app, browser, screen}) => {
  const cwd = await t3.project("demo");
  const thread = await t3.thread({project: cwd, title: "Shell startup paste", messages: ["hello"]});
  const shell = `${cwd}/startup-shell`;
  await writeFile(`${cwd}/startup.rc`, `PS1='READY$ '\nprintf 'Continue startup? [y/n] '\nread answer\nprintf 'startup got answer: [%s]\\n' "$answer"\nprintf 'Starting line editor (8s)...\\n'\nprintf answered > '${cwd}/answered'\nsleep 8\nprintf 'Line editor starting now\\n'\n`);
  await writeFile(shell, `#!/bin/sh\nexec /bin/bash --noprofile --rcfile '${cwd}/startup.rc' -i\n`);
  await chmod(shell, 0o755);
  const target = {threadId: ThreadId.make(thread.threadId), terminalId: DEFAULT_TERMINAL_ID};
  const open = () => runPromise(rpcClient(T3_HOME, app.baseUrl ?? "").pipe(Effect.flatMap(client => client["terminal.open"]({...target, cwd, env: {T3CODE_TERMINAL_SHELL: shell}})), Effect.scoped));
  await open();
  await browser.emulateMedia({colorScheme: "dark"});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByLabel("Terminal input");
  // The surface can appear before its viewer accepts input; answer only until the shell confirms it.
  await expect.poll(async () => {
    const answered = await readFile(`${cwd}/answered`, "utf8").catch(() => "");
    if (answered) return answered;
    await input.focus();
    await browser.keyboard.type("y");
    await browser.keyboard.press("Enter");
    return readFile(`${cwd}/answered`, "utf8").catch(() => "");
  }).toBe("answered");
  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;
  }, LINE);
  await browser.keyboard.press("Enter");
  // The reproduction waits through shell startup and the server's held-input release.
  await new Promise(resolve => setTimeout(resolve, 22000));
  await app.screenshot("single-enter-after-startup-paste");
  const snapshot = await open();
  // Snapshot serialization can position rows with cursor escapes instead of newlines.
  // One marker is the echoed command; the second is the command's actual output.
  expect(snapshot.history.split("PASTED-COMMAND-RAN").length - 1).toBe(2);
});
