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

test("Empty quoted heredoc names the following printf in the live activity row", WEB, async ({t3, app, screen}) => {
  const project = await t3.project("Heredoc label");
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await FS.readFile(settingsPath, "utf8"));
  settings.providerInstances.cursor = {driver:"cursor",enabled:true};
  await FS.writeFile(settingsPath, JSON.stringify(settings));
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client.subscribeServerConfig({}).pipe(Stream.filter(event =>
      (event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : []).some(p => p.instanceId === "cursor" && p.enabled)
    ), Stream.runHead);
  }).pipe(Effect.scoped));
  const {cli} = makeState(T3_HOME);
  const script = "cd . <<''\npretend\n\nprintf ok; sleep 25";
  const started = await runPromise(cli(["thread","start",project,
    `Run exactly this bash script once, as a single shell command. Preserve the two consecutive newline characters after pretend (the empty line ends the heredoc). Do not add a wrapper, preflight commands, or alter the script.\n\n${script}`,
    "--title","Empty quoted heredoc","--provider","cursor","--model","auto","--json"]));
  const {threadId} = JSON.parse(started.stdout);
  await t3.open({threadId});
  await screen.getByText(/^Running (command|printf)$/).first().waitFor({timeout:120000});
  await app.screenshot("live-heredoc-label");
  await expect(screen.getByText("Running printf", {exact:true})).toBeVisible();
});
