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";

test("Here-strings preserve the following printf live work label", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("shell-label-proof");
  const seed = await t3.thread({ project, title: "Ready", messages: ["Start"] });
  const settingsPath = Path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await FS.readFile(settingsPath, "utf8"));
  settings.providerInstances.claudeAgent = { driver: "claudeAgent", enabled: true, config: { binaryPath: "/usr/local/bin/claude" } };
  await FS.writeFile(settingsPath, JSON.stringify(settings));
  await t3.open(seed);
  const failures: string[] = [];
  for (const [label, command] of [
    ["newline-here-string", ": <<< hi\nprintf '%s' visible\nsleep 60"],
    ["attached-here-string", ": <<<-hi && printf '%s' visible && sleep 60"],
    ["control", ": && printf '%s' visible && sleep 60"],
  ]) {
    const prompt = `Execute exactly this script in one Bash tool call. Do not edit it or run any other commands. The sleep keeps the live work label visible for a UI check.\n\n${command}`;
    const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, prompt, "--title", label, "--provider", "claudeAgent", "--model", "haiku", "--json"]));
    await t3.open(JSON.parse(started.stdout));
    await screen.getByText(/^Running (command|printf)$/).first().waitFor({ timeout: 90000 });
    await app.screenshot(label);
    try { await expect(screen.getByText("Running printf", { exact: true }).first()).toBeVisible(); }
    catch { failures.push(label); }
    await screen.getByRole("button", "Stop generation").tap();
  }
  expect(failures).toEqual([]);
});
