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

test("HTML comments do not supply a plan title or open a code fence", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("proj");
  const transcript = path.join(project, "plan-replay.ndjson");
  const script = path.join(project, "plan-replay.ts");
  const source = await fs.readFile(path.join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"), "utf8");
  await fs.writeFile(script, source.replace(
    "const scenario = SCENARIOS.find((candidate) => candidate.id === scenarioId) ?? SCENARIOS[0];",
    `const scenario = { file: ${JSON.stringify(transcript)} };`,
  ));
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const originalSettings = await fs.readFile(settingsPath, "utf8");
  const settings = JSON.parse(originalSettings);
  settings.providerInstances.devReplay.config.commandArgs = [script];
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const fixtures = [
    { label: "commented-code-fence", markdown: "<!--\n```ts\n-->\n# Release plan\n\n- Tag the release\n- Publish the changelog" },
    { label: "commented-heading", markdown: "<!--\n# Hidden title\n-->\n# Release plan\n\n- Tag the release\n- Publish the changelog" },
  ];
  const threads = [];
  try {
    for (const fixture of fixtures) {
      const records = [
        { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
        { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "fixture", update: { sessionUpdate: "plan_update", plan: { type: "markdown", planId: "release", content: fixture.markdown } } } } },
        { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "fixture", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "The release plan is ready." } } } } },
        { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
      ];
      await fs.writeFile(transcript, records.map(record => JSON.stringify(record)).join("\n") + "\n");
      threads.push(await t3.thread({ project, title: fixture.label === "commented-code-fence" ? "Release checklist" : "Commented heading", messages: ["Prepare the release plan."], model: "multi-turn" }));
    }
  } finally {
    await fs.writeFile(settingsPath, originalSettings);
  }
  const observed = [];
  for (const [index, thread] of threads.entries()) {
    await t3.open(thread);
    await screen.getByRole("button", "Plan actions").waitFor({ timeout: 120_000 });
    await screen.getByText("The release plan is ready.", { exact: true }).waitFor();
    await screen.getByText("Syncing messages...", { exact: false }).waitFor({ state: "hidden" });
    await app.screenshot(fixtures[index]!.label);
    const title = await browser.evaluate(() => document.querySelector("h3[data-thread-find-text]")?.textContent);
    await screen.getByRole("button", "Plan actions").tap();
    const download = await browser.waitForDownload(() => screen.getByRole("menuitem", "Download as markdown").tap());
    const filename = download.suggestedFilename;
    observed.push({ title, filename });
  }
  expect(observed).toEqual([
    { title: "Release plan", filename: "release-plan.md" },
    { title: "Release plan", filename: "release-plan.md" },
  ]);
});
