/// <reference lib="dom" />
// @effect-diagnostics nodeBuiltinImport:off -- The scenario stages a local ACP executable.
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";

import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";

import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";


// Generic ACP input reproduces the triage stream; no vendor-specific behavior is involved.
const ACP = `
import { createInterface } from "node:readline";
const sessionId = "paragraph-stream";
let turns = 0;
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
const chunk = (text) => send({ method: "session/update", params: { sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } });
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
for await (const line of createInterface({ input: process.stdin })) {
  const { id, method, params } = JSON.parse(line);
  if (id === undefined) continue;
  if (method === "initialize") send({ id, result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] } });
  else if (method === "session/new") send({ id, result: { sessionId } });
  else if (method === "session/prompt") {
    if (turns++ === 0) chunk("Ready for paragraph streaming.");
    else {
      const lf = JSON.stringify(params.prompt).includes("LF control");
      await delay(300);
      chunk(lf ? "Intro paragraph (LF separated).\\n\\nBody" : "Intro paragraph (CR separated).\\r\\rBody");
      for (let i = 0; i < 40; i++) { await delay(200); chunk(" continuing"); }
      chunk(" done.");
    }
    send({ id, result: { stopReason: "end_turn" } });
  } else send({ id, result: {} });
}
`;

test("Completed CR paragraphs render while body chunks continue", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("paragraph-demo");
  const script = NodePath.join(project, "paragraph-acp.mjs");
  const settingsPath = NodePath.join(T3_HOME, "userdata/settings.json");
  const originalSettings = await NodeFSP.readFile(settingsPath, "utf8");
  const settings = JSON.parse(originalSettings);
  await NodeFSP.writeFile(script, ACP);
  settings.providerInstances["paragraph-agent"] = {
    driver: "acpRegistry", displayName: "Paragraph stream", enabled: true,
    config: { source: "local", commandPath: process.execPath, commandArgs: [script] },
  };
  try {
    await NodeFSP.writeFile(settingsPath, JSON.stringify(settings));
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client.subscribeServerConfig({}).pipe(Stream.filter(event =>
        (event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [])
          .some(provider => provider.instanceId === "paragraph-agent")), Stream.runHead);
    }).pipe(Effect.scoped));
    const { cli } = makeState(T3_HOME);
    const started = await runPromise(cli(["thread", "start", project, "Prepare streaming demo", "--title", "Paragraph streaming", "--provider", "paragraph-agent", "--model", "default", "--wait", "--json"]));
    const { threadId } = JSON.parse(started.stdout);
    await t3.open({ threadId });
    await screen.getByText("Ready for paragraph streaming.", { exact: true }).waitFor({ timeout: 60000 });
    let crVisible = false;
    for (const [prompt, label, intro] of [
      ["CR run: stream a CR-separated intro and keep the body arriving", "CR-while-streaming", "Intro paragraph (CR separated)."],
      ["LF control: stream an LF-separated intro and keep the body arriving", "LF-while-streaming", "Intro paragraph (LF separated)."],
    ]) {
      const composer = screen.getByRole("textbox");
      await composer.fill(prompt);
      await composer.press("Enter");
      const stop = screen.getByRole("button", "Stop generation");
      await stop.waitFor({ timeout: 30000 });
      // The bug depends on continuous arrivals: inspect at 3 s, before the 8.3 s completion.
      await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 3000)));
      await app.screenshot(label);
      const visible = await browser.evaluate((text) => document.body.innerText.includes(text), intro);
      if (label.startsWith("CR")) crVisible = visible;
      await stop.waitFor({ state: "hidden", timeout: 30000 });
      await app.screenshot(label.replace("while-streaming", "completed"));
    }
    await expect(crVisible).toBe(true);
  } finally {
    await NodeFSP.writeFile(settingsPath, originalSettings);
  }
});
