/// <reference lib="dom" />
import { existsSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Terminal-restored worktree runs synchronous setup before the next turn", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo", { "README.md": "Terminal worktree restore demo\n" });
  const { cli } = makeState(T3_HOME);
  const start = await runPromise(cli(["thread", "start", project, "Start", "--title", "Start", "--worktree", "main", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]));
  const thread = JSON.parse(start.stdout) as { threadId: string };
  const worktrees = execFileSync("git", ["worktree", "list", "--porcelain"], { cwd: project, encoding: "utf8" });
  const checkout = worktrees.split("\n").filter(line => line.startsWith("worktree ")).map(line => line.slice(9)).find(path => path !== project)!;
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    yield* client["server.updateSettings"]({ patch: { defaultProjectScripts: [{ id: "prepare", name: "Prepare", command: "sleep 2 && date > setup-ready", icon: "play", runOnWorktreeCreate: true, async: false }] } });
  }).pipe(Effect.scoped));
  await t3.open(thread);
  execFileSync("git", ["worktree", "remove", checkout], { cwd: project });
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await terminal.waitFor();
  // The shell prompt confirms terminal launch has completed the restore before sending.
  await terminal.focus();
  await browser.keyboard.type("printf 'Terminal restored checkout\\n'");
  await browser.keyboard.press("Enter");
  await runPromise(cli(["thread", "send", thread.threadId, "Continue here", "--wait", "--json"]));
  await screen.getByText("second fixture turn complete", { exact: false }).first().waitFor({ timeout: 60000 });
  await terminal.focus();
  await browser.keyboard.type("PS1='$ '; printf '\\033[2J\\033[H'; printf 'After terminal restore and completed follow-up:\\n'; if test -e setup-ready; then printf 'setup-ready PRESENT: setup ran before turn completed\\n'; else printf 'setup-ready MISSING: setup did not run\\n'; fi");
  await browser.keyboard.press("Enter");
  const terminalText = 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");
    return browser.evaluate(() => document.body.dataset.terminalCopy ?? "");
  };
  // Wait for the diagnostic command, then capture the same result on either side.
  for (let attempt = 0; attempt < 50; attempt++) {
    if ((await terminalText()).includes(existsSync(`${checkout}/setup-ready`) ? "setup-ready PRESENT:" : "setup-ready MISSING:")) break;
  }
  await browser.keyboard.press("ArrowRight");
  await app.screenshot("setup-after-terminal-restore");
  expect(existsSync(`${checkout}/setup-ready`)).toBe(true);
});
