import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const command = ': <<"E\\X"\nhello\nE\\X\nprintf ok; sleep 60';
test("A literal backslash in a quoted heredoc delimiter keeps the following printf visible", WEB, async ({t3, app, screen}) => {
  const project = await t3.project("heredoc-demo");
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath,"utf8"));
  settings.providerInstances.opencode = {driver:"opencode",enabled:true,config:{binaryPath:"opencode"}};
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const started = await runPromise(makeState(T3_HOME).cli(["thread","start",project,
    'Use exactly one Bash tool call with this exact command, preserving all literal backslashes and newlines:\n' + command + '\nDo not emit any text before the tool call. After it finishes, explain briefly. Do not make other tool calls.',
    "--title","Literal heredoc delimiter","--provider","opencode","--model","anthropic/claude-haiku-5-5","--json"]));
  const {threadId} = JSON.parse(started.stdout);
  await t3.open({threadId});
  await screen.getByText(/^Running (command|printf)$/).waitFor({timeout:120000});
  await screen.getByText("Syncing messages...", {exact:true}).waitFor({state:"hidden"});
  await screen.getByRole("button", "Agent Use exactly one Bash tool call", {exact:false}).tap();
  await app.screenshot("live-heredoc-command");
  await expect(screen.getByText("Running printf", {exact:true})).toBeVisible();
});
