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

const TABLE = "| Name | Amount |\n| --- | ---: |\n| Al | 7 |\n| Beatrice | 1200 |\n| Christopher | 42 |";
const EXPECTED = "```\nName         Amount\n-----------  ------\nAl                7\nBeatrice       1200\nChristopher      42\n```";

test("Copy a table as aligned text for chat apps", WEB, async ({ t3, app, screen, browser }) => {
  // The free replay agent supplies the same synthetic assistant table on both commits.
  const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: TABLE } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  try {
    await fs.writeFile(fixture, frames.map(x => JSON.stringify(x)).join("\n") + "\n");
    const project = await t3.project("Table-copy-demo");
    const thread = await t3.thread({ project, title: "Amounts", model: "showcase", messages: ["Show the names and amounts as a table."] });
    await t3.open(thread);
    await screen.getByRole("cell", "Christopher", { exact: true }).waitFor({ timeout: 120_000 });
    await screen.getByRole("button", "Copy table", { exact: true }).tap();
    await screen.getByRole("menuitem", "Copy as Markdown", { exact: true }).waitFor();
    await app.screenshot("copy-table-menu");
    const hasChat = await browser.evaluate(() => [...document.querySelectorAll('[role="menuitem"]')].some(el => el.textContent?.includes("Copy for chat apps")));
    await screen.getByRole("menuitem", hasChat ? "Copy for chat apps" : "Copy as Markdown", { exact: true }).tap();
    await browser.evaluate(() => {
      document.addEventListener("paste", event => {
        document.documentElement.dataset.pastedPlain = event.clipboardData?.getData("text/plain") ?? "";
        document.documentElement.dataset.pastedHtml = event.clipboardData?.getData("text/html") ?? "";
      }, { once: true });
    });
    await screen.getByRole("textbox").tap();
    await browser.keyboard.press("Control+v");
    await app.screenshot("pasted-table");
    const pasted = await browser.evaluate(() => ({ text: document.documentElement.dataset.pastedPlain ?? "", html: document.documentElement.dataset.pastedHtml ?? "" }));
    expect(pasted.text).toBe(EXPECTED);
    expect(pasted.html).toContain("<pre>");
    expect(pasted.html).toContain("Christopher");
  } finally {
    await fs.writeFile(fixture, original);
  }
});
