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("Collapsed reasoning keeps a well-formed emoji boundary", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1280, height: 1200 });
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const rows = original.trimEnd().split("\n").map((line) => JSON.parse(line));
  for (const row of rows) {
    const update = row.frame?.params?.update;
    if (update?.sessionUpdate === "agent_thought_chunk") update.content.text = "x".repeat(2047) + "😀 tail";
  }
  await writeFile(fixture, rows.map((row) => JSON.stringify(row).replaceAll("<workspace>/", "")).join("\n") + "\n");
  try {
    const project = await t3.project("emoji-preview", { "src/math.ts": "export const sum = 1 + 1;\n" });
    await t3.thread({ project, title: "Emoji boundary", messages: ["Give me a short tour"], model: "showcase" });
    await t3.open();
    await screen.getByRole("button", "Emoji boundary, Done, emoji-preview").tap();
    await screen.getByRole("button", /Worked for/).tap();
    const preview = browser.locator("span.chat-markdown").filter({ hasText: "xxxxxxxxxxxxxxxx" }).first();
    await preview.waitFor({ state: "visible" });
    await app.screenshot("collapsed-reasoning");
    // Reveal the existing preview with wrapping for capture; do not change its text.
    await browser.evaluate(() => {
      const el = Array.from(document.querySelectorAll("span.chat-markdown")).find((node) => node.textContent?.startsWith("xxxxxxxx"));
      const parent = el?.closest("span.truncate");
      if (parent instanceof HTMLElement && el instanceof HTMLElement) {
        parent.style.whiteSpace = "normal";
        parent.style.overflow = "visible";
        parent.style.textOverflow = "clip";
        el.style.whiteSpace = "normal";
        el.style.overflowWrap = "anywhere";
      }
    });
    await app.screenshot("preview-boundary");
    const boundary = await browser.evaluate(() => {
      const el = Array.from(document.querySelectorAll("span.chat-markdown")).find((node) => node.textContent?.startsWith("xxxxxxxx"));
      const text = el?.textContent ?? "";
      return { length: text.length, wellFormed: text.isWellFormed(), lastCodeUnit: text.charCodeAt(text.length - 1) };
    });
    console.log("Collapsed preview boundary:", boundary);
    await expect(boundary.wellFormed).toBe(true);
  } finally {
    await writeFile(fixture, original);
  }
});
