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 { makeState, runPromise, test, WEB } from "./t3.ts";

test("Completed newline reply displays and finds the empty response", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  const script = path.join(project, "newline-agent.ts");
  const fixture = path.join(project, "newline.ndjson");
  const replay = await fs.readFile(path.join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"), "utf8");
  await fs.writeFile(script, replay.replace(/export const SCENARIOS = \[[\s\S]*?\] as const;/, 'export const SCENARIOS = [{ id: "newline", name: "Newline reply", file: "./newline.ndjson" }] as const;'));
  await fs.writeFile(fixture, [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
    { type: "emit_inbound", afterMs: 2000, frame: { kind: "notification", method: "session/update", params: { sessionId: "newline", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "\n" } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map(x => JSON.stringify(x)).join("\n"));
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const original = await fs.readFile(settingsPath, "utf8");
  const settings = JSON.parse(original);
  settings.providerInstances["newline-agent"] = { driver: "acpRegistry", displayName: "Newline agent", enabled: true, config: { source: "local", commandPath: process.execPath, commandArgs: [script] } };
  try {
    await fs.writeFile(settingsPath, JSON.stringify(settings));
    const { cli } = makeState(T3_HOME);
    let threadId: string | undefined;
    for (let i = 0; i < 8 && !threadId; i++) {
      const started = await runPromise(cli(["thread", "start", project, "Say nothing", "--title", "Newline reply", "--provider", "newline-agent", "--model", "newline", "--wait", "--json"], [0, 1]));
      if (!started.stdout.includes("threadId")) continue;
      const result = JSON.parse(started.stdout);
      if (result.status !== "completed") throw new Error(`Turn did not complete: ${started.stdout}`);
      threadId = result.threadId;
    }
    if (!threadId) throw new Error("Could not start newline turn");
    await t3.open({ threadId });
    await screen.getByText("Say nothing", { exact: true }).waitFor();
    await browser.keyboard.press("Control+f");
    await screen.getByRole("searchbox", "Find in thread").fill("empty response");
    try {
      await expect.poll(() => browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""')).toBe("1/1");
      await expect(screen.getByText("(empty response)", { exact: true })).toBeVisible();
    } finally {
      await app.screenshot("newline-empty-response-and-find");
    }
  } finally {
    await fs.writeFile(settingsPath, original);
  }
});
