import { readFile } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { runPromise, test, WEB } from "./t3.ts";

test("Terminal sends focus reports while DECSET 1004 is enabled", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("terminal-demo");
  const thread = await t3.thread({project, title: "Terminal focus", messages: ["hello"]});
  const read = (file: string) => runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    return yield* fs.readFileString(`${project}/${file}`);
  }).pipe(Effect.orElseSucceed(() => "")));
  const capture = async (label: string) => {
    await delay(700);
    let previous = await app.screenshot(`${label}-settling`);
    for (let i = 0; i < 6; i++) {
      await delay(500);
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error("Terminal capture did not settle");
  };
  await browser.emulateMedia({ reducedMotion: "reduce" });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle main sidebar").tap();
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  const composer = screen.getByRole("textbox", "Message Terminal focus");
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("export PS1='$ '; echo ready > shell-ready");
    await browser.keyboard.press("Enter");
    return read("shell-ready");
  }, {timeout: 30000}).toBe("ready\n");
  await browser.keyboard.type("printf '\\033[?25l\\033[2J\\033[HFocus reporting enabled (DECSET 1004)\\n'; stty -echo -icanon; printf '\\033[?1004h'; echo ready > mode-ready; cat -v | tee focus-reports");
  await browser.keyboard.press("Enter");
  await expect.poll(() => read("mode-ready")).toBe("ready\n");
  await delay(1500);
  await composer.tap();
  await delay(750);
  await browser.locator('canvas:has(~ textarea[aria-label="Terminal input"])').tap();
  await browser.keyboard.type("\n");
  await capture("enabled-focus-reports");
  const enabled = await read("focus-reports");
  await browser.keyboard.press("Control+c");
  await browser.keyboard.type("printf '\\033[?1004l'; stty sane; printf '\\nFocus reporting disabled\\n'; stty -echo -icanon; cat -v | tee disabled-reports");
  await browser.keyboard.press("Enter");
  await browser.keyboard.type("ready\n");
  await expect.poll(() => read("disabled-reports")).toBe("ready\n");
  await delay(1500);
  await composer.tap();
  await delay(750);
  await browser.locator('canvas:has(~ textarea[aria-label="Terminal input"])').tap();
  await browser.keyboard.type("done\n");
  await expect.poll(() => read("disabled-reports")).toBe("ready\ndone\n");
  await capture("disabled-focus-reports");
  await browser.keyboard.press("Control+c");
  await browser.keyboard.type("printf '\\033[?1004l\\033[?25h'; stty sane");
  await browser.keyboard.press("Enter");
  expect(enabled).toBe("^[[O^[[I\n");
});
