/// <reference lib="dom" />
import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const reply = '<p dir="rtl">Hello world!</p>\n<p dir="ltr">مرحبا بالعالم!</p>\n<p>Hello world!</p>\n<p>مرحبا بالعالم!</p>';

test("Markdown preserves authored paragraph directions", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("markdown-demo");
  // Supply the exact reported assistant reply through the real replay provider.
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", id: 1, params: {} } },
    { 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", id: 1, result: { stopReason: "end_turn" } } },
  ];
  let thread;
  try {
    await writeFile(fixture, frames.map((frame) => JSON.stringify(frame)).join("\n") + "\n");
    thread = await t3.thread({ project, title: "Authored HTML directions", messages: ["Reply verbatim with these four HTML paragraphs, without a code fence:\n" + reply], model: "command-output" });
  } finally {
    await writeFile(fixture, original);
  }
  await t3.open(thread);
  await screen.getByText("Hello world!", { exact: true }).first().waitFor();
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  const directions = await browser.evaluate(() => [...document.querySelectorAll('.chat-markdown p')].filter((p) => p.textContent === "Hello world!" || p.textContent === "مرحبا بالعالم!").map((p) => ({ text: p.textContent, dir: p.getAttribute("dir"), computed: getComputedStyle(p).direction })));
  await app.screenshot("authored-html-directions");
  expect(directions).toEqual([
    { text: "Hello world!", dir: "rtl", computed: "rtl" },
    { text: "مرحبا بالعالم!", dir: "ltr", computed: "ltr" },
    { text: "Hello world!", dir: "ltr", computed: "ltr" },
    { text: "مرحبا بالعالم!", dir: "rtl", computed: "rtl" },
  ]);
});
