import { writeFileSync } from "node:fs";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Standalone images separate find text for CRLF, CR and LF", WEB, async ({ t3, app, screen, browser }) => {
  const variants = [["Crlf", "\r\n"], ["Cr", "\r"], ["Lf", "\n"]];
  const entries = variants.flatMap(([name, ending]) => [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: `Caption${name}${ending}![pic](https://x.test/pic.png)${ending}After${name}` } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ]);
  writeFileSync(`${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`, entries.map(x => JSON.stringify(x)).join("\n") + "\n");
  const project = await t3.project("image-boundaries");
  const thread = await t3.thread({ project, title: "CRLF image", messages: ["Show CRLF reply", "Show CR reply", "Show LF reply"], model: "showcase" });
  await t3.open(thread);
  await screen.getByText("AfterLf", { exact: false }).waitFor({ timeout: 120_000 });
  await browser.keyboard.press("Control+f");
  const results: string[] = [];
  for (const [name] of variants) {
    await screen.getByRole("searchbox", "Find in thread").fill(`Caption${name}  After${name}`);
    // Wait for the debounced search to render the current query.
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 700)));
    results.push(await browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""'));
    await app.screenshot(`${name}-image-boundary`);
  }
  expect(results).toEqual(["0/0", "0/0", "0/0"]);
});
