/// <reference lib="dom" />
import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("New interactive terminals use the configured shell executable", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("terminal-demo");
  const thread = await t3.thread({project, title:"Interactive shell", messages:["Check the terminal shell"]});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle thread details panel").tap();
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByRole("textbox", "Terminal input");
  await expect(terminal).toHaveAttribute("data-workspace-focus-default", "");
  await terminal.focus();
  await browser.keyboard.type("PS1='> '; clear; { printf 'Interactive shell probe\\n'; printf 'Executable: '; readlink /proc/$$/exe; printf 'BASH_VERSION=%s\\n' \"${BASH_VERSION:-unset}\"; printf 'PROBE_DONE\\n'; } | tee shell-probe.txt; printf '\\033[?25l'\n");
  const result = () => readFile(`${project}/shell-probe.txt`, "utf8").catch(() => "");
  await expect.poll(result, {timeout:30000}).toContain("PROBE_DONE");
  await browser.mouse.move(900,50);
  const label=process.env.PROBE_LABEL ?? "configured-shell";
  let previous=await app.screenshot(`${label}-settling-0`);
  let stable=false;
  for(let i=1;i<=15;i++) {
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve,500)));
    const next=await app.screenshot(`${label}-settling-${i}`);
    if((await readFile(previous)).equals(await readFile(next))) {stable=true;break;}
    previous=next;
  }
  if(!stable)throw new Error("The capture did not stabilize");
  await app.screenshot(label);
  await expect.poll(result).toContain(process.env.PROBE_EXPECTED ?? "/usr/bin/dash");
});
