/// <reference lib="dom" />
import { 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 PROGRAM = String.raw`import { writeFileSync } from 'node:fs';
process.stdin.setRawMode(true);
const state = value => writeFileSync('state', value);
process.stdout.write('\x1b[2J\x1b[HReady for split-control reproduction\r\n');
state('started');
process.stdin.on('data', chunk => {
  const key = chunk.toString();
  {
    if (key === 'o') {
      process.stdout.write('\x1b[2J\x1b[HOSC title is unfinished; clear now\r\n\x1b]0;Build ', () => state('osc-pending'));
    }
    if (key === 'p') {
      process.stdout.write('progress\x07ready-OSC\r\n', () => state('osc-complete'));
    }
    if (key === 'i') {
      process.stdout.write('\x1b[2J\x1b[HCSI is unfinished; six line feeds already executed\r\n\x1b[\n\n\n\n\n\n', () => state('csi-pending'));
    }
    if (key === 'm') {
      process.stdout.write('mready-CSI\r\n', () => state('csi-complete'));
    }
    if (key === 'x') process.exit(42);
  }
});
`;

test("Clearing a split OSC or CSI keeps attached and reattached terminals correct", WEB, async ({ t3, app, browser, screen }) => {
  const cwd = await t3.project("terminal-proof", { "proof.mjs": PROGRAM });
  const thread = await t3.thread({ project: cwd, title: "Split terminal controls", messages: ["hello"] });
  const input = { threadId: ThreadId.make(thread.threadId), terminalId: "term-1" };
  const rpc = (method: "terminal.open" | "terminal.write" | "terminal.clear", extra = {}) => runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    return yield* client[method]({ ...input, ...extra } as never);
  }).pipe(Effect.scoped));
  const readState = () => runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    return yield* fs.readFileString(`${cwd}/state`);
  }).pipe(Effect.orElseSucceed(() => "")));
  await rpc("terminal.open", { cwd, env: { PS1: "proof> ", PROMPT_COMMAND: "", TERM: "xterm-256color" } });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await expect(terminal).toHaveAttribute("data-workspace-focus-default", "");
  await expect.poll(async () => {
    await rpc("terminal.write", { data: "stty -echo; exec node proof.mjs\r" });
    return readState();
  }, { timeout: 30_000 }).toBe("started");
  const text = 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");
    const value = await browser.evaluate(() => document.body.dataset.terminalCopy ?? "");
    await browser.keyboard.press("ArrowRight");
    return value;
  };
  const results: Record<string, string> = {};
  for (const [name, start, finish] of [["osc", "o", "p"], ["csi", "i", "m"]]) {
    await rpc("terminal.write", { data: start });
    await expect.poll(readState).toBe(`${name}-pending`);
    await app.screenshot(`${name}-unfinished-before-clear`);
    // This is the same shared Clear RPC as the mobile toolbar, while the web view stays attached.
    await rpc("terminal.clear");
    await rpc("terminal.write", { data: finish });
    await expect.poll(readState).toBe(`${name}-complete`);
    await expect.poll(text).toContain(`ready-${name.toUpperCase()}`);
    results[`${name}-attached`] = (await text()).trim();
    await app.screenshot(`${name}-attached-after-clear`);
    await t3.open("/settings/general");
    await t3.open(thread);
    await terminal.waitFor();
    await expect.poll(text).toContain(`ready-${name.toUpperCase()}`);
    results[`${name}-reattached`] = (await text()).trim();
    await app.screenshot(`${name}-reattached-after-clear`);
  }
  expect(results).toEqual({ "osc-attached": "ready-OSC", "osc-reattached": "ready-OSC", "csi-attached": "ready-CSI", "csi-reattached": "ready-CSI" });
});
