// @effect-diagnostics nodeBuiltinImport:off -- Seed a local recording for the dev Replay agent.
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";

import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";

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

const textUpdate = (text: string, afterMs = 0) => ({
  type: "emit_inbound", afterMs,
  frame: { kind: "notification", method: "session/update", params: {
    sessionId: "<session-id>", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } }
  } }
});
const transcript = [
  { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
  textUpdate("> quote\n★ Insight ───\n\n  ★ Insight ───\n───\n\noutside"),
  ...[" still", " streaming", " this", " paragraph", " slowly", " now", " done."].map(word => textUpdate(word, 3000)),
  { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
].map(entry => JSON.stringify(entry)).join("\n");

test(
  "Streamed Insight keeps its trailing paragraph after a skipped opener",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const replayAgent = await NodeFSP.readFile(
      new URL("../../apps/server/scripts/dev-replay-agent.ts", import.meta.url),
      "utf8",
    );
    const project = await t3.project("demo", {
      "replay/dev-replay-agent.ts": replayAgent,
      "replay/dev-replay/showcase_transcript.ndjson": transcript,
    });
    const instanceId = ProviderInstanceId.make("scenario-insight-agent");
    await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
        yield* client["server.updateSettings"]({
          patch: {},
          providerInstanceMutation: {
            operation: "upsert",
            instanceId,
            instance: {
              driver: ProviderDriverKind.make("acpRegistry"),
              displayName: "Insight replay",
              enabled: true,
              config: {
                source: "local",
                commandPath: process.execPath,
                commandArgs: [NodePath.join(project, "replay/dev-replay-agent.ts")],
              },
            },
          },
        });
      }).pipe(Effect.scoped),
    );
    const { cli } = makeState(T3_HOME);
    const started = await runPromise(
      cli([
        "thread",
        "start",
        project,
        "Show the Insight callout reproduction.",
        "--title",
        "Streamed Insight",
        "--provider",
        instanceId,
        "--model",
        "default",
        "--json",
      ]),
    );
    const { threadId } = JSON.parse(started.stdout) as { threadId: string };
    await t3.open({ threadId });

    await screen.getByText("outside still streaming", { exact: false }).waitFor();
    const streamingInside = await browser.evaluate(() =>
      [...document.querySelectorAll('[role="note"]')].some(note => note.textContent?.includes("outside still streaming"))
    );
    await app.screenshot("streaming-insight");
    await screen.getByText("outside still streaming this paragraph slowly now done.", { exact: true }).waitFor();
    await screen.getByRole("button", "Submit message", { exact: true }).waitFor();
    await app.screenshot("settled-insight");
    expect(streamingInside).toBe(true);
  },
);
