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("Bare URLs stop before Chinese punctuation and preserve bold", WEB, async ({ t3, app, screen, browser }) => {
  const reply = "可以看了：**http://localhost:18780**（已重启，跑的是提交后的版本）。\n\n打开 http://localhost:18780，然后刷新";
  const recording = join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await readFile(recording, "utf8");
  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: reply } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  try {
    await writeFile(recording, frames.map(frame => JSON.stringify(frame)).join("\n") + "\n");
    const project = await t3.project("URL punctuation");
    await t3.thread({ project, title: "Chinese URL boundaries", messages: ["Reply with the two URL examples exactly as supplied."], model: "showcase" });
  } finally {
    await writeFile(recording, original);
  }
  await t3.open();
  await screen.getByRole("button", "Chinese URL boundaries, Done, URL punctuation").tap();
  await screen.getByText("可以看了：", { exact: false }).first().waitFor({ state: "visible" });
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("cjk-url-boundaries");
  const links = await browser.evaluate(() => Array.from(document.querySelectorAll('a[href^="http://localhost:18780"]')).map(a => ({ href: a.getAttribute("href"), text: a.textContent, bold: Boolean(a.closest("strong") || a.querySelector("strong")) })));
  expect(links).toEqual([
    { href: "http://localhost:18780", text: "http://localhost:18780", bold: true },
    { href: "http://localhost:18780", text: "http://localhost:18780", bold: false },
  ]);
});
