import { expect } from "e2e";
import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Settling a fork preserves its active source's shared worktree files", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("shared-worktree-demo", {
    ".gitignore": "dist/\nproof.done\n",
    "t3.json": JSON.stringify({ scripts: [{ name: "Clean", command: "rm -rf dist && echo cleaned", runOnSettle: true }] }),
  });
  const cli = (args: string[]) => runPromise(makeState(T3_HOME).cli(args));
  const started = await cli(["thread", "start", project, "first", "--title", "Source thread", "--worktree", "main", "--branch", "demo-source", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]);
  const source = JSON.parse(started.stdout);
  const state = JSON.parse((await cli(["thread", "show", source.threadId, "--json"])).stdout);
  const worktree = state.thread.worktreePath;
  if (!worktree) throw new Error("Source must use a worktree");
  mkdirSync(`${worktree}/dist`, { recursive: true });
  writeFileSync(`${worktree}/dist/keep.txt`, "Source build artifact survives fork settlement\n");
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(source);
  await screen.getByRole("button", "Choose project action", { exact: true }).tap();
  await screen.getByRole("menuitem", /Clean/).tap();
  await screen.getByRole("button", "Fork from this response").first().tap();
  const forkActions = screen.getByRole("button", "Thread actions for Source thread fork");
  await forkActions.waitFor();
  await forkActions.tap();
  await screen.getByRole("menuitem", "Settle thread", { exact: true }).tap();
  await screen.getByRole("button", "Un-settle", { exact: true }).waitFor();
  // Let the UI finish applying the settlement, then inspect from the active source's real terminal.
  await t3.open(source);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await input.waitFor();
  await browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]').waitFor();
  await input.focus();
  await browser.keyboard.type("export PS1=''; clear; printf 'SOURCE THREAD: still active\\nFORK: settled\\nSettle action: rm -rf dist && echo cleaned\\n\\nChecking shared source worktree after fork settlement:\\n'; if test -f dist/keep.txt; then cat dist/keep.txt; else echo 'BUG: dist/keep.txt was deleted by fork settlement'; fi; echo complete > proof.done\n");
  await input.press("Enter");
  // The command completion file is a synchronization marker, not the behavior assertion.
  const deadline = Date.now() + 15000;
  while (!existsSync(`${worktree}/proof.done`) && Date.now() < deadline) await new Promise(r => setTimeout(r, 100));
  if (!existsSync(`${worktree}/proof.done`)) throw new Error("Terminal inspection did not finish");
  await app.screenshot("shared-worktree-after-fork-settlement");
  expect(existsSync(`${worktree}/dist/keep.txt`), "Settling the fork must preserve the active source's dist/keep.txt").toBe(true);
});
