/// <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 reply = 'List:\n\n-       :codex-file-citation{path="src/a.ts"}\n-       :codex-followup[Run tests]{prompt="Run tests"}\n\nControl (one space):\n\n- :codex-file-citation{path="src/a.ts"}\n- :codex-followup[Run tests]{prompt="Run tests"}';

test("Codex directives render in over-indented list items", WEB, async ({ t3, app, browser, screen }) => {
  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: reply } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  try {
    await fs.writeFile(fixture, frames.map((f) => JSON.stringify(f)).join("\n") + "\n");
    const project = await t3.project("directive-demo", { "src/a.ts": "export const value = 1;\n" });
    const thread = await t3.thread({ project, title: "Codex list directives", model: "showcase", messages: ["Show the list directives and control."] });
    await browser.emulateMedia({ colorScheme: "dark" });
    await t3.open(thread);
    await screen.getByText("Control (one space):", { exact: true }).waitFor();
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot("codex-list-directives");
    const items = await browser.evaluate(() => Array.from(document.querySelectorAll("li"), (li) => li.textContent?.trim() ?? "").filter((s) => s.includes("a.ts") || s.includes("Run tests")));
    expect(items).toEqual(["a.ts", "Run tests", "a.ts", "Run tests"]);
  } finally {
    await fs.writeFile(fixture, original);
  }
});
