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

test("Backticked insights preserve body lines and search boundaries", WEB, async ({ t3, app, screen, browser }) => {
  const bodies = [
    "Backticked opener:\n\n`★ Insight ─────`\nfirst line\nsecond line\nthird line\n`─────`",
    "Bare opener:\n\n★ Insight ─────\nfirst line\nsecond line\nthird line\n─────",
  ];
  const transcript = bodies.flatMap((text) => [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: {} } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "fixture", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ]).map((entry) => JSON.stringify(entry)).join("\n");
  writeFileSync(join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson"), transcript);
  const project = await t3.project("insight-demo");
  const thread = await t3.thread({ project, title: "Insight line breaks", model: "command-output", messages: ["Show the backticked insight", "Show the bare control"] });
  await t3.open(thread);
  await screen.getByText("Bare opener:", { exact: false }).waitFor();
  await app.screenshot("insight-body-lines");
  const rendered = await browser.evaluate(() => [...document.querySelectorAll<HTMLElement>("p")].filter((p) => p.textContent?.includes("first line") && !p.closest("[data-user-message-body]")).map((p) => p.innerText));
  await browser.keyboard.press("Control+f");
  await screen.getByRole("searchbox", "Find in thread").fill("line second");
  try {
    await expect.poll(() => browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""')).toBe("0/0");
    expect(rendered).toEqual(["first line\nsecond line\nthird line", "first line\nsecond line\nthird line"]);
  } finally {
    await app.screenshot("insight-search-boundaries");
  }
});
