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

test("Shell -s highlights its heredoc with positional arguments", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("shell-demo");
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.claudeAgent.enabled = true;
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project,
    "Run exactly this as one Bash tool call, verbatim, with no extra commands:\nbash -euxs -- prod <<'EOF'\necho \"$1\"\nEOF\nThen reply only: Done.",
    "--title", "Shell heredoc with arguments", "--provider", "claudeAgent", "--model", "claude-haiku-5-5", "--wait", "--json"]));
  const { threadId } = JSON.parse(started.stdout);
  await t3.open({ threadId });
  await screen.getByRole("button", "Worked for", { exact: false }).tap();
  const group = screen.getByRole("button", "Ran 1 command", { exact: false });
  if (await group.count()) await group.tap();
  await screen.getByRole("button", "bash -euxs -- prod <<'EOF'\necho \"$1\"\nEOF", { exact: true }).tap();
  await expect.poll(() => browser.evaluate(() => {
    return Array.from(document.querySelectorAll("span[style]")).some(e => e.textContent === "bash" && getComputedStyle(e).color !== "rgb(57, 58, 52)");
  })).toBe(true);
  await app.screenshot("expanded-shell-heredoc");
  await expect.poll(() => browser.evaluate(() => {
    const spans = Array.from(document.querySelectorAll("span[style]"));
    const echo = spans.find(e => e.textContent === "echo");
    const eof = spans.findLast(e => e.textContent === "EOF");
    return echo && eof ? getComputedStyle(echo).color !== getComputedStyle(eof).color : false;
  })).toBe(true);
});
