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

const MESSAGE = "Draft plan: alpha beta gamma delta. Please review this draft.";

test("Selecting send_to_user text offers Cite", WEB, async ({ t3, app, browser, screen }) => {
  // Replay the provider's successful tool result through the real ACP adapter and projections.
  const update = (value: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: value } } });
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    update({ sessionUpdate: "tool_call", toolCallId: "send-draft", kind: "other", title: "mcp__t3_code__send_to_user", status: "in_progress", rawInput: { message: MESSAGE } }),
    update({ sessionUpdate: "tool_call_update", toolCallId: "send-draft", status: "completed", rawOutput: JSON.stringify({ sentMessage: MESSAGE, message: "Shown to the user. Don't repeat it." }) }),
    update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "done" } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  writeFileSync(join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson"), frames.map((frame) => JSON.stringify(frame)).join("\n") + "\n");
  const project = await t3.project("Citation demo");
  const thread = await t3.thread({ project, title: "Review the draft", messages: ["Send the draft with send_to_user, then reply done."], model: "showcase" });
  await t3.open(thread);
  await screen.getByText(MESSAGE, { exact: true }).waitFor({ state: "visible" });
  const box = await browser.evaluate(() => {
    const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
    while (walker.nextNode()) {
      const node = walker.currentNode;
      const index = node.textContent?.indexOf("gamma") ?? -1;
      if (index < 0) continue;
      const range = document.createRange();
      range.setStart(node, index);
      range.setEnd(node, index + 5);
      const rect = range.getBoundingClientRect();
      if (rect.width > 0) return { x: rect.x, y: rect.y + rect.height / 2, end: rect.right };
    }
    throw new Error("Draft word gamma is not rendered");
  });
  await browser.mouse.move(box.x, box.y);
  await browser.mouse.down();
  await browser.mouse.move(box.end, box.y);
  await browser.mouse.up();
  await app.screenshot("draft-text-selected");
  await expect(screen.getByRole("button", "Cite selection in composer")).toBeVisible();
});
