import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
async function pidFile(path: string) {
  for (let i = 0; i < 100; i++) {
    try { return Number((await readFile(path, "utf8")).trim()); } catch { await delay(100); }
  }
  throw new Error("Terminal command did not write its READY PID");
}
const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };

test("Settlement preserves exec and foreground Bash commands waiting for input", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("terminal-proof");
  const thread = await t3.thread({project, title: "Active terminal settlement", messages: ["Prepare terminal proof"]});
  await t3.open(thread);
  const threadPath = await browser.evaluate(() => location.pathname);
  await screen.getByRole("button", "Toggle terminal drawer", {exact: true}).tap();
  await browser.locator('[data-thread-terminal-drawer] canvas').last().tap();
  await browser.keyboard.type(`PS1='proof$ '; clear; bash -c 'echo $$ > foreground.pid; printf "FOREGROUND BASH READY\\nWaiting for input\\n"; read -r value; printf "Input received: %s\\n" "$value"'`);
  await browser.keyboard.press("Enter");
  const foregroundPid = await pidFile(`${project}/foreground.pid`);
  await screen.getByRole("button", "Split Terminal Horizontally", {exact: false}).tap();
  await browser.locator('[data-thread-terminal-drawer] canvas').last().tap();
  await browser.keyboard.type(`PS1='proof$ '; clear; exec node -e 'require("fs").writeFileSync("exec.pid", String(process.pid)); console.log("EXEC NODE READY\\nWaiting for input"); process.stdin.on("data", data => console.log("Input received: " + data.toString().trim())); process.stdin.resume()'`);
  await browser.keyboard.press("Enter");
  const execPid = await pidFile(`${project}/exec.pid`);
  await delay(1000);
  await app.screenshot("commands-ready");
  await screen.getByRole("button", "Active terminal settlement, terminal-proof", {exact: true}).hover();
  await screen.getByRole("button", "Settle thread", {exact: true}).tap();
  await delay(3000);
  // Return to the same settled thread so closed drawers and surviving sessions are visible.
  await app.open(threadPath);
  await screen.getByRole("button", "Un-settle", {exact: true}).waitFor({state: "visible"});
  await screen.getByText("Syncing messages...", {exact: true}).waitFor({state: "hidden"});
  await delay(500);
  await app.screenshot("after-settlement");
  expect({foregroundBashAlive: alive(foregroundPid), execNodeAlive: alive(execPid)}).toEqual({foregroundBashAlive: true, execNodeAlive: true});
});
