// @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 answer = "Let me be clear: no files were changed, and the original data is intact.";
const followUp =
  "I also checked the backup schedule. It runs each night after the reporting job finishes, and the dashboard lists the last seven successful runs. The latest backup finished this morning. If you need older copies, they are listed separately in the archive.";

const textUpdate = (sessionUpdate: string, text: string) => ({
  type: "emit_inbound",
  frame: {
    kind: "notification",
    method: "session/update",
    params: {
      sessionId: "<session-id>",
      update: { sessionUpdate, content: { type: "text", text } },
    },
  },
});

const transcript = [
  { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
  textUpdate("agent_message_chunk", answer),
  textUpdate("agent_thought_chunk", "Add the requested details on the backup schedule."),
  textUpdate("agent_message_chunk", followUp),
  {
    type: "emit_inbound",
    frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } },
  },
]
  .map((entry) => JSON.stringify(entry))
  .join("\n");

test(
  "An ACP answer still shows after the agent continues and the turn collapses",
  WEB,
  async ({ t3, app, screen }) => {
    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-short-answer-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: "Short answer fixture",
              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,
        "Were any files changed? Also check the backup schedule.",
        "--title",
        "File integrity and backups",
        "--provider",
        instanceId,
        "--model",
        "default",
        "--wait",
        "--json",
      ]),
    );
    const { threadId } = JSON.parse(started.stdout) as { threadId: string };
    await t3.open({ threadId });

    await screen.getByText(followUp, { exact: true }).waitFor();
    const fold = screen.getByRole("button", /^Worked/);
    await fold.tap();
    const firstAnswer = screen.getByText(answer, { exact: true });
    await firstAnswer.waitFor();
    await fold.tap();
    await expect(fold).toHaveAttribute("aria-expanded", "false");

    await app.screenshot("collapsed-turn");
    await expect(firstAnswer).toBeVisible();
  },
);
