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

test("A BOM-prefixed plan keeps its title and strips its heading from the body", WEB, async ({ t3, app, screen }) => {
  const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  const notification = (update: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "bom-plan", update } } });
  const entries = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    notification({ sessionUpdate: "plan_update", plan: { type: "markdown", planId: "rollout", content: "\uFEFF# Rollout\n\nDeploy" } }),
    notification({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "The rollout plan is ready." } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  try {
    await fs.writeFile(fixture, entries.map((entry) => JSON.stringify(entry)).join("\n") + "\n");
    const project = await t3.project("demo");
    const thread = await t3.thread({ project, title: "Rollout planning", model: "showcase", messages: ["Prepare the rollout plan"] });
    await t3.open(thread);
    await screen.getByText("The rollout plan is ready.", { exact: true }).waitFor();
    await screen.getByText("Deploy", { exact: true }).waitFor();
    await app.screenshot("bom-plan");
    await expect(screen.getByText("Proposed plan", { exact: true })).toBeHidden();
    await expect(screen.getByText("Rollout", { exact: true })).toBeVisible();
    await expect(screen.getByRole("heading", "Rollout", { exact: true, level: 4 })).toBeHidden();
  } finally {
    await fs.writeFile(fixture, original);
  }
});
