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

test("Reference definitions resolve before streaming ends", WEB, async ({ t3, app, screen }) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await fs.readFile(fixture, "utf8");
  const prompt = { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } };
  const end = { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } };
  const chunk = (text: string, thought = false, afterMs = 30) => ({ type: "emit_inbound", afterMs, frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: thought ? "agent_thought_chunk" : "agent_message_chunk", content: { type: "text", text } } } } });
  const turn = (text: string) => [prompt, chunk(text), chunk("\n\n" + (text.includes(">") ? "Quoted definition received." : "Multiline definition received.")), ...Array.from({ length: 3 }, () => chunk(" ", false, 2000)), end];
  await fs.writeFile(fixture, [...turn("See [ref].\n\n> [ref]: https://example.com"), ...turn("See [multi line].\n\n[multi\nline]: https://example.com")].map(x => JSON.stringify(x)).join("\n"));
  try {
    await t3.project("demo");
    await t3.open();
    const composer = screen.getByTestId("composer-editor");
    await composer.fill("Show the quoted reference");
    await composer.press("Enter");
    await screen.getByText("See", { exact: false }).first().waitFor();
    await screen.getByRole("button", "Stop generation").waitFor();
    // The marker follows the complete definition in the same streamed message.
    await screen.getByText("Quoted definition received.", { exact: true }).waitFor();
    await app.screenshot("blockquote-streaming");
    const quotedLinks = await screen.getByRole("link", "ref", { exact: true }).count();
    await screen.getByRole("button", "Stop generation").waitFor({ state: "detached" });
    await composer.fill("again");
    await composer.press("Enter");
    await screen.getByText("See", { exact: false }).last().waitFor();
    await screen.getByRole("button", "Stop generation").waitFor();
    await screen.getByText("Multiline definition received.", { exact: true }).waitFor();
    await app.screenshot("multiline-streaming");
    const multilineLinks = await screen.getByRole("link", "multi line", { exact: true }).count();
    expect({ quotedLinks, multilineLinks }).toEqual({ quotedLinks: 1, multilineLinks: 1 });
  } finally {
    await fs.writeFile(fixture, original);
  }
});
