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("Rename inspector shows both paths relative to the project", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("repo", { "src/old-name.ts": "export const name = 'old';\n" });
  const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  const oldPath = path.join(project, "src/old-name.ts");
  const newPath = path.join(project, "src/new-name.ts");
  const update = (update: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update } } });
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    update({ sessionUpdate: "tool_call", toolCallId: "rename", kind: "edit", title: "Rename file", status: "completed", content: [{ type: "diff", path: oldPath, oldText: "export const name = 'old';\n", newText: "export const name = 'new';\n", changes: [{ operation: "update", oldPath, path: newPath }] }] }),
    update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Renamed src/old-name.ts to src/new-name.ts." } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  try {
    await fs.rename(oldPath, newPath);
    await fs.writeFile(newPath, "export const name = 'new';\n");
    await fs.writeFile(fixture, frames.map((frame) => JSON.stringify(frame)).join("\n") + "\n");
    const thread = await t3.thread({ project, title: "Rename a TypeScript file", messages: ["Rename src/old-name.ts to src/new-name.ts and update its value"], model: "command-output" });
    await t3.open(thread);
    await screen.getByText("Renamed src/old-name.ts to src/new-name.ts.", { exact: true }).waitFor();
    await screen.getByRole("button", "Worked for", { exact: false }).tap();
    await screen.getByRole("button", "Changed 1 file", { exact: false }).tap();
    await screen.getByText(/update .*old-name\.ts → .*new-name\.ts/).waitFor();
    await app.screenshot("rename-inspector");
    await expect(screen.getByText("update repo/src/old-name.ts → repo/src/new-name.ts", { exact: true })).toBeVisible();
  } finally {
    await fs.writeFile(fixture, original);
  }
});
