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

test("An external Markdown link keeps its leading emoji intact", WEB, async ({ t3, app, screen, browser }) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const markdown = "[😀 Read the documentation](https://example.com)";
  const frames = [
    { 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: markdown } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  try {
    await writeFile(fixture, frames.map((frame) => JSON.stringify(frame)).join("\n") + "\n");
    const project = await t3.project("link-demo");
    await t3.thread({ project, title: "Emoji link", model: "showcase", messages: [`Emit this Markdown as rendered prose outside a code block: ${markdown}`] });
    await t3.open();
    await browser.locator("[data-sidebar-row]").first().waitFor({ state: "visible", timeout: 120000 });
    await browser.locator("[data-sidebar-row]").first().press("Enter");
    await screen.getByRole("link", "😀 Read the documentation").first().waitFor({ state: "visible" });
    await screen.getByText("Syncing messages...", { exact: false }).waitFor({ state: "hidden", timeout: 60000 });
    await browser.evaluate(async () => { await document.fonts.ready; });
    await app.screenshot("emoji-link");
    const textNodes = await browser.evaluate(() => {
      const link = document.querySelector('a[href="https://example.com"]');
      if (!link) throw new Error("Rendered external link missing");
      const walker = document.createTreeWalker(link, NodeFilter.SHOW_TEXT);
      const nodes: string[] = [];
      while (walker.nextNode()) {
        const value = walker.currentNode.nodeValue ?? "";
        nodes.push(value);
      }
      return nodes;
    });
    const brokenNodes = textNodes.filter((value) => /\p{Surrogate}/u.test(value));
    await writeFile(new URL(`../.e2e/emoji-dom-${brokenNodes.length ? "base" : "head"}.json`, import.meta.url), JSON.stringify({ markdown, textNodes, loneSurrogates: brokenNodes }, null, 2));
    expect(brokenNodes).toEqual([]);
  } finally {
    await writeFile(fixture, original);
  }
});
