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

test("Home paths stay outside the workspace in Read and Edit rows", WEB, async ({ t3, app, screen }) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = readFileSync(fixture, "utf8");
  const frames: unknown[] = [{ type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } }];
  const update = (value: unknown) => frames.push({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: value } } });
  for (const [index, path] of ["~/.claude/CLAUDE.md", "~\\.gitconfig", "src/app.ts"].entries()) {
    update({ sessionUpdate: "tool_call", toolCallId: `read-${index}`, kind: "read", title: `Read ${path}`, status: "pending", rawInput: { path } });
    update({ sessionUpdate: "tool_call_update", toolCallId: `read-${index}`, status: "completed", content: [{ type: "content", content: { type: "text", text: "Synthetic file contents" } }] });
  }
  const diff = [{ type: "diff", path: "~/.claude/CLAUDE.md", oldText: "Old instruction\n", newText: "New instruction\n" }];
  update({ sessionUpdate: "tool_call", toolCallId: "edit-home", kind: "edit", title: "Edit ~/.claude/CLAUDE.md", status: "pending", rawInput: { path: "~/.claude/CLAUDE.md" }, content: diff });
  update({ sessionUpdate: "tool_call_update", toolCallId: "edit-home", status: "completed", content: diff });
  update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Home path demonstration complete." } });
  frames.push({ type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } });
  writeFileSync(fixture, frames.map((frame) => JSON.stringify(frame)).join("\n") + "\n");
  try {
    const project = await t3.project("demo", { "src/app.ts": "export const app = true;\n" });
    const thread = await t3.thread({ project, title: "Home path demonstration", messages: ["Read the home instructions, git config and app, then edit the home instructions."], model: "showcase" });
    await t3.open(thread);
    await screen.getByRole("button", /^Worked for/).tap();
    await screen.getByRole("button", "Read 3 files and changed 1 file").tap();
    await screen.getByRole("button", /^Read .*CLAUDE.md/).tap();
    await app.screenshot("home-paths");
    await expect(screen.getByText("/~ /".replace(" ", ""), { exact: false })).toHaveCount(0);
    await expect(screen.getByText("Read ~/.gitconfig", { exact: true })).toBeVisible();
  } finally {
    writeFileSync(fixture, original);
  }
});
