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

test("Shell executable casing does not appear in command rows", WEB, async ({ t3, app, screen }) => {
  const fixture = join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await readFile(fixture, "utf8");
  const lines = original.trim().split("\n").map((line) => JSON.parse(line));
  const emit = (update: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update } } });
  const calls = ['Bash.exe -lc "git status"', 'BASH.EXE -lc "npm test"', 'bash -lc "git status"'].flatMap((command, i) => [
    emit({ sessionUpdate: "tool_call", toolCallId: `shell-${i}`, kind: "execute", title: command, status: "in_progress", rawInput: { command } }),
    emit({ sessionUpdate: "tool_call_update", toolCallId: `shell-${i}`, status: "completed", rawOutput: "Completed successfully.\n" }),
  ]);
  await writeFile(fixture, [...lines.slice(0, 2), ...calls, emit({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Three shell commands completed." } }), lines.at(-1)].map((line) => JSON.stringify(line)).join("\n") + "\n");
  try {
    const project = await t3.project("shell-demo");
    const thread = await t3.thread({ project, title: "Shell command display", messages: ["go"], model: "command-output" });
    await t3.open(thread);
    await screen.getByRole("button", "Worked for", { exact: false }).tap();
    await screen.getByRole("button", "Ran 3 commands", { exact: false }).tap();
    await app.screenshot("shell-command-rows");
    await expect(screen.getByRole("button", "npm test", { exact: true })).toBeVisible();
    await expect(screen.getByRole("button", 'Bash.exe -lc "git status"', { exact: false })).not.toBeVisible();
  } finally {
    await writeFile(fixture, original);
  }
});
