import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";

export async function prepareAcpWhitespaceReplay(APP_DIR: string) {
  const agentPath = join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts");
  const originalAgent = await readFile(agentPath, "utf8");
  const fixturePaths = [
    join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson"),
    join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/todo_list/registry_transcript.ndjson"),
  ];
  const chunk = (messageId: string, text: string) => ({ sessionUpdate: "agent_message_chunk", messageId, content: { type: "text", text } });
  const full = (messageId: string, text: string) => ({ sessionUpdate: "agent_message", messageId, content: [{ type: "text", text }] });
  const transcript = (updates: unknown[]) => [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    ...updates.map((update) => ({ type: "emit_inbound", afterMs: 1000, frame: { kind: "notification", method: "session/update", params: { sessionId: "synthetic", update } } })),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map((entry) => JSON.stringify(entry)).join("\n") + "\n";
  await writeFile(agentPath, originalAgent.replace('const REPLAYED_UPDATES = new Set([', 'const REPLAYED_UPDATES = new Set([\n  "agent_message",'));
  await writeFile(fixturePaths[0]!, transcript([chunk("answer", "A"), chunk(" answer ", "B")]));
  await writeFile(fixturePaths[1]!, transcript([full(" answer ", "A"), chunk(" answer ", "B")]));
}
