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

test("Uppercase combined shell flags highlight the quoted script", WEB, async ({ t3, app, screen, browser }) => {
  const commands = ["bash -Ec 'echo hi'", "bash -ec 'echo hi'", "sh -Cc 'echo hi'"];
  const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  const update = (value: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: value } } });
  const frames: unknown[] = [{ type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } }];
  for (const [index, command] of commands.entries()) {
    frames.push(update({ sessionUpdate: "tool_call", toolCallId: `shell-${index}`, kind: "execute", title: command, status: "in_progress", rawInput: { command } }));
    frames.push(update({ sessionUpdate: "tool_call_update", toolCallId: `shell-${index}`, status: "completed", rawOutput: "hi\n" }));
  }
  frames.push(update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "All three commands printed hi." } }));
  frames.push({ type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } });
  await fs.writeFile(fixture, frames.map(value => JSON.stringify(value)).join("\n"));
  try {
    const project = await t3.project("shell-demo");
    const thread = await t3.thread({ project, title: "Shell flag highlighting", messages: ["Run bash -Ec, bash -ec and sh -Cc with echo hi, one command each."], model: "command-output" });
    await t3.open(thread);
    await screen.getByText("All three commands printed hi.", { exact: true }).waitFor();
    await screen.getByRole("button", "Worked for", { exact: false }).tap();
    await screen.getByRole("button", "Ran 3 commands", { exact: false }).tap();
    for (let index = 0; index < 3; index++) await screen.getByRole("button", "echo hi", { exact: true }).nth(index).tap();
    await screen.getByText("sh", { exact: true }).waitFor();
    await app.screenshot("shell-flags");
    await expect.poll(() => browser.evaluate(() => {
      const blocks = Array.from(document.querySelectorAll("div.text-foreground\\/85"));
      return ["bash -Ec 'echo hi'", "bash -ec 'echo hi'", "sh -Cc 'echo hi'"].map(command => {
        const block = blocks.find(element => element.textContent?.trim() === command);
        if (!block) return false;
        const spans = Array.from(block.querySelectorAll("span"));
        const interpreter = spans.find(span => span.style.color && span.textContent === command.split(" ")[0]);
        const echo = spans.find(span => span.style.color && span.textContent === "echo");
        return Boolean(interpreter && echo && getComputedStyle(interpreter).color === getComputedStyle(echo).color);
      });
    })).toEqual([true, true, true]);
  } finally { await fs.writeFile(fixture, original); }
});
