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

const plan = "## ###\n\n## Release checklist\n\nUpdate the release notes.";

test("Empty closing-hash headings are skipped in plan previews and downloads", WEB, async ({ t3, app, browser, screen }) => {
  // Supply identical synthetic model output to each app through the real Replay ACP adapter.
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: { sessionUpdate: "plan_update", plan: { type: "markdown", planId: "release-plan", content: plan } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  await writeFile(fixture, frames.map((frame) => JSON.stringify(frame)).join("\n"));
  try {
    const project = await t3.project("release-demo");
    const thread = await t3.thread({ project, title: "Release plan", model: "showcase", messages: ["Prepare the release checklist plan."] });
    await t3.open(thread);
    await screen.getByRole("button", "Plan actions", { exact: true }).waitFor();
    await screen.getByRole("button", "Plan actions", { exact: true }).tap();
    const download = await browser.waitForDownload(() => screen.getByRole("menuitem", "Download as markdown", { exact: true }).tap());
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot("plan-preview-and-download");
    expect(download.suggestedFilename).toBe("release-checklist.md");
    await expect(screen.getByRole("heading", "Release checklist", { exact: true })).toBeVisible();
    expect(await browser.evaluate(() => [...document.querySelectorAll("h3")].filter((h) => h.textContent === "Release checklist").length)).toBe(1);
    expect(await browser.evaluate(() => [...document.querySelectorAll("h5")].filter((h) => h.textContent === "Release checklist").length)).toBe(0);
  } finally {
    await writeFile(fixture, original);
  }
});
