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("Split bash wrappers show their script in the work log", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("command-demo");
  const recording = path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await fs.readFile(recording, "utf8");
  const commands = ['bash \\\n-lc "git status"', 'bash\\\n -lc "git status"', 'bash -lc "git status"', 'bash -lc "git status \\\n--short"'];
  const rows: Array<{ threadId: string }> = [];
  try {
    for (const [index, command] of commands.entries()) {
      const update = (value: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: value } } });
      const frames = [
        { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
        update({ sessionUpdate: "tool_call", toolCallId: "bash", kind: "execute", title: command, status: "in_progress", rawInput: { command } }),
        update({ sessionUpdate: "tool_call_update", toolCallId: "bash", status: "completed", rawOutput: "On branch main\nnothing to commit, working tree clean" }),
        update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Command completed." } }),
        { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
      ];
      await fs.writeFile(recording, frames.map(value => JSON.stringify(value)).join("\n") + "\n");
      rows.push(await t3.thread({ project, title: ["split A", "split 2", "single-line control", "quoted-script continuation"][index]!, messages: ["Run the exact bash command:\n" + command], model: "command-output" }));
    }
    for (const [index, thread] of rows.entries()) {
      await t3.open(thread);
      await screen.getByText("Command completed.", { exact: true }).waitFor();
      await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
      await screen.getByRole("button", "Worked for", { exact: false }).tap();
      await app.screenshot(["split-a", "split-2", "single-line-control", "quoted-script"][index]!);
    }
    for (const [index, thread] of rows.entries()) {
      await t3.open(thread);
      await screen.getByText("Command completed.", { exact: true }).waitFor();
      const worked = screen.getByRole("button", "Worked for", { exact: false });
      await worked.tap();
      await expect(screen.getByRole("button", index === 3 ? "git status --short" : "git status", { exact: true })).toBeVisible();
    }
  } finally { await fs.writeFile(recording, original); }
});
