// @effect-diagnostics nodeBuiltinImport:off -- The scenario stages a local Replay recording.
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";

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

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

const fixture = (separator: string) => [
  { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
  { type: "emit_inbound", frame: { kind: "notification", method: "session/update",
    params: { sessionId: "<session-id>", update: { sessionUpdate: "plan_update",
      plan: { type: "markdown", planId: "plan", content: ["# Plan", ...Array.from({ length: 21 }, (_, i) => "- Step " + (i + 1))].join(separator) } } } } },
  { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
].map((entry) => JSON.stringify(entry)).join("\n");

test(
  "Long plans collapse with LF, CRLF, and bare CR",
  WEB,
  async ({ t3, app, browser, screen }) => {
    await browser.setViewport({ width: 1280, height: 1100 });
    const agent = await NodeFSP.readFile(
      NodePath.join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"),
      "utf8",
    );
    const project = await t3.project("demo", {
      "replay.ts": agent,
      "dev-replay/showcase_transcript.ndjson": fixture("\n"),
    });
    const instanceId = ProviderInstanceId.make("devReplay");
    const original = await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
        const settings = yield* client["server.getSettings"]({});
        const instance = settings.providerInstances[instanceId];
        if (instance === undefined) throw new Error("Replay provider is missing");
        return instance;
      }).pipe(Effect.scoped),
    );
    const setReplay = (instance: typeof original) =>
      runPromise(
        Effect.gen(function* () {
          const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
          yield* client["server.updateSettings"]({
            patch: {},
            providerInstanceMutation: { operation: "upsert", instanceId, instance },
          });
        }).pipe(Effect.scoped),
      );

    try {
      await setReplay({
        ...original,
        config: {
          source: "local",
          commandPath: process.execPath,
          commandArgs: [NodePath.join(project, "replay.ts")],
        },
      });
      for (const [label, separator] of [["LF", "\n"], ["CRLF", "\r\n"], ["CR", "\r"]]) {
        await NodeFSP.writeFile(NodePath.join(project, "dev-replay/showcase_transcript.ndjson"), fixture(separator));
        const thread = await t3.thread({
          project, title: label + " plan", messages: ["Propose the plan."], model: "showcase",
        });
        await t3.open(thread);
        await screen.getByText("Step 1", { exact: true }).waitFor();
        await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
        const expand = screen.getByRole("button", "Expand plan", { exact: true });
        await app.screenshot(label + "-initial");
        expect(await expand.count(), label + " offers Expand plan").toBe(1);
        await expand.click();
        await app.screenshot(label + "-expanded");
        await expect(screen.getByText("Step 21", { exact: true })).toBeVisible();
      }
    } finally {
      await setReplay(original);
    }
  },
);
