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";

const reply = "منشور على https://example.com/report، ونسخته\nهل يعمل **http://localhost:3000**؟ نعم؛ www.example.com۔";

test("Bare URLs stop before Arabic punctuation and preserve bold", WEB, async ({ t3, app, screen, browser }) => {
  const fixture = join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await readFile(fixture, "utf8");
  const transcript = [
    { 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" } } },
  ].map((entry) => JSON.stringify(entry)).join("\n") + "\n";
  await writeFile(fixture, transcript);
  try {
    const project = await t3.project("Arabic Markdown");
    const thread = await t3.thread({ project, title: "Arabic URL punctuation", model: "showcase", messages: ["Reply with exactly the following two lines as plain Markdown, verbatim, with no code block and nothing else:\n" + reply] });
    await t3.open(thread);
    await screen.getByText("منشور على", { exact: false }).last().waitFor({ state: "visible" });
    await screen.getByText("Syncing messages...", { exact: false }).waitFor({ state: "hidden" });
    await app.screenshot("arabic-url-rendering");
    const rendered = await browser.evaluate(() => ({
      links: Array.from(document.querySelectorAll("a")).filter((a) => /example\.com|localhost:3000/.test(a.href)).map((a) => ({ text: a.textContent, href: a.getAttribute("href"), bold: !!a.closest("strong") })),
    }));
    expect(rendered).toEqual({ links: [
      { text: "https://example.com/report", href: "https://example.com/report", bold: false },
      { text: "http://localhost:3000", href: "http://localhost:3000", bold: true },
      { text: "www.example.com", href: "http://www.example.com", bold: false },
    ] });
  } finally {
    await writeFile(fixture, original);
  }
});
