import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("An assistant link to an unconnected environment does not open a blank pane", WEB, async ({ t3, app, screen, browser }) => {
  const transcript = join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await readFile(transcript, "utf8");
  const text = "Related work is on the other machine:\n\n<t3-thread://v2/peer-environment-0001/mcp:launch:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef>\n\nOpen that conversation to continue.";
  const recording = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map((entry) => JSON.stringify(entry)).join("\n");
  // Only the replayed assistant text changes; the application code under test is unchanged.
  await writeFile(transcript, recording + "\n");
  try {
    const project = await t3.project("Thread link demo");
    await t3.thread({ project, title: "Local conversation", messages: ["Where is the related work?"], model: "showcase" });
    await t3.open();
    await screen.getByRole("button", "Local conversation, Done, Thread link demo").tap();
    await screen.getByText("Open that conversation to continue.", { exact: false }).waitFor({ state: "visible" });
    await screen.getByText("Syncing messages…", { exact: false }).waitFor({ state: "hidden" });
    await new Promise((resolve) => setTimeout(resolve, 1500));
    await app.screenshot("assistant-thread-link");
    await new Promise((resolve) => setTimeout(resolve, 2500));
    // Click the chip when it is a link; an explanatory unresolved chip has no navigation action.
    await browser.evaluate(() => {
      const link = document.querySelector('a[href^="/peer-environment-0001/"]');
      if (link instanceof HTMLElement) link.click();
    });
    await new Promise((resolve) => setTimeout(resolve, 8500));
    await app.screenshot("after-thread-link");
    await expect(screen.getByText("Thread on another machine", { exact: true })).toBeVisible();
  } finally {
    await writeFile(transcript, original);
  }
});
