/// <reference lib="dom" />
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("NUL padding preserves command output escapes and red text", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("escape-output", {
    "pad-after-esc.sh": "printf 'A\\033\\000[31mB\\033[0mC\\n'\n",
    "pad-in-csi.sh": "printf 'A\\033[3\\0001mB\\033[0mC\\n'\n",
    "pad-charset.sh": "printf 'A\\033(\\000BC\\n'\n",
    "control.sh": "printf 'A\\033[31mB\\033[0mC\\n'\n",
  });
  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 { cli } = makeState(T3_HOME);
  const started = await runPromise(cli([
    "thread", "start", project,
    "Run exactly these four commands as four separate shell tool calls: bash pad-after-esc.sh; bash pad-in-csi.sh; bash pad-charset.sh; bash control.sh. Do not combine commands, do not pipe or transform output. Then reply with only Done.",
    "--title", "NUL padded escape output", "--provider", "opencode", "--model", "anthropic/claude-haiku-4-5-20251001", "--wait", "--json",
  ]));
  const { threadId } = JSON.parse(started.stdout);
  await browser.emulateMedia({ colorScheme: "light" });
  await t3.open({ threadId });
  await screen.getByRole("button", "Worked for", { exact: false }).tap();
  // The command group is present only when the timeline folds several calls together.
  const group = screen.getByRole("button", "Ran 4 commands", { exact: false });
  if (await group.isVisible()) await group.tap();
  for (const name of ["pad-after-esc.sh", "pad-in-csi.sh", "pad-charset.sh", "control.sh"]) {
    await screen.getByRole("button", `bash ${name}`, { exact: true }).tap();
  }
  await screen.getByText("ABC", { exact: false }).last().waitFor();
  await app.screenshot("expanded-command-output");
  const outputs = await browser.evaluate(() => Array.from(document.querySelectorAll("div.max-h-80.overflow-auto.text-muted-foreground")).map((el) => ({
    text: el.textContent,
    red: Array.from(el.querySelectorAll("span")).filter((span) => span.textContent === "B").map((span) => getComputedStyle(span).color),
  })));
  expect(outputs).toEqual([
    { text: "ABC\n", red: ["rgb(207, 34, 46)"] },
    { text: "ABC\n", red: ["rgb(207, 34, 46)"] },
    { text: "AC\n", red: [] },
    { text: "ABC\n", red: ["rgb(207, 34, 46)"] },
  ]);
});
