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

test("Long paste after answering real Bash startup prompt", WEB, async ({ t3, app, browser, screen }) => {
  const cwd = await t3.project("terminal-demo");
  const thread = await t3.thread({ project: cwd, title: "Long paste during Bash startup", messages: ["hello"] });
  const read = (name: string) => readFile(`${cwd}/${name}`, "utf8").catch(() => "");
  await writeFile(`${cwd}/startup.rc`, `read -r -p "Continue startup? [y/n] " answer\necho "answered: $answer; starting 15-second startup wait"\nprintf %s "$answer" > answer\nsleep 15\necho "startup done"\nPS1='repro$ '\n`);
  await writeFile(`${cwd}/startup-shell`, `#!/bin/sh\ncd '${cwd}'\nexec /bin/bash --noprofile --rcfile '${cwd}/startup.rc' -i\n`);
  await chmod(`${cwd}/startup-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: `${cwd}/startup-shell`}})), Effect.scoped));
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByLabel("Terminal input");
  await new Promise(resolve => setTimeout(resolve, 1500));
  await input.focus();
  await browser.keyboard.type("y");
  await browser.keyboard.press("Enter");
  await expect.poll(() => read("answer")).toBe("y");
  await new Promise(resolve => setTimeout(resolve, 2000));
  const command = `> pasted.txt printf %s ${"x".repeat(5000)}\n`;
  await browser.evaluate(async (text) => navigator.clipboard.writeText(text), command);
  await browser.keyboard.press("Control+Shift+v");
  await expect.poll(() => read("pasted.txt")).not.toBe("");
  await browser.keyboard.type("printf '\\nPASTE RESULT: '; wc -c < pasted.txt\n");
  await new Promise(resolve => setTimeout(resolve, 1000));
  await app.screenshot("long-paste-byte-count");
  expect((await read("pasted.txt")).length).toBe(5000);
});
