import { writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Expanded command output preserves Unicode terminal cells", WEB, async ({ t3, app, screen }) => {
  const command = "printf '😀\\033[1Gx\\n界a\\033[3GZ\\ne\\xcc\\x81a\\033[2GZ\\n'";
  const output = execFileSync("bash", ["-c", command], { encoding: "utf8" });
  const update = (value: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: value } } });
  const transcript = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    update({ sessionUpdate: "tool_call", toolCallId: "unicode", kind: "execute", title: command, status: "in_progress", rawInput: { command } }),
    update({ sessionUpdate: "tool_call_update", toolCallId: "unicode", status: "completed", rawOutput: output }),
    update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Unicode command complete." } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  // Identical raw printf bytes enter the real replay adapter on both app revisions.
  writeFileSync(`${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`, transcript.map(row => JSON.stringify(row)).join("\n") + "\n");
  const project = await t3.project("unicode-demo");
  const thread = await t3.thread({ project, title: "Unicode command output", messages: ["Run the Unicode printf command"], model: "command-output" });
  await t3.open(thread);
  await screen.getByRole("button", "Worked for", { exact: false }).tap();
  await screen.getByRole("button", command, { exact: true }).tap();
  await screen.getByText("Unicode command complete.", { exact: true }).waitFor({ state: "visible" });
  await app.screenshot("unicode-overwrites");
  await expect(screen.getByText("x 界Z éZ", { exact: true })).toBeVisible();
});
