// @effect-diagnostics nodeBuiltinImport:off -- Seed synthetic assistant text through 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 cases = [
  { name: "Form feed", separator: "\f" },
  { name: "Vertical tab", separator: "\v" },
  { name: "Plain space", separator: " " },
];
const transcript = (text: 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: "agent_message_chunk", content: { type: "text", text } },
  } } },
  { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
].map(entry => JSON.stringify(entry)).join("\n");

test("File links retain distinguishing folders after control whitespace", WEB, async ({ t3, app, screen }) => {
  const replayAgent = await NodeFSP.readFile(new URL("../../apps/server/scripts/dev-replay-agent.ts", import.meta.url), "utf8");
  const files: Record<string, string> = { "one/a.ts": "export const one = 1;", "two/a.ts": "export const two = 2;" };
  for (const [index, { name, separator }] of cases.entries()) {
    files[`replay-${index}/dev-replay-agent.ts`] = replayAgent;
    files[`replay-${index}/dev-replay/showcase_transcript.ndjson`] = transcript(`Separator: ${name}. See [a.ts](./one/a.ts${separator}"title") and [a.ts](./two/a.ts).`);
  }
  const project = await t3.project("workspace", files);
  const threads = [];
  for (const [index, { name }] of cases.entries()) {
    const instanceId = ProviderInstanceId.make(`scenario-links-${index}`);
    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: "Replay file links", enabled: true,
          config: { source: "local", commandPath: process.execPath, commandArgs: [NodePath.join(project, `replay-${index}/dev-replay-agent.ts`)] },
        },
      } });
    }).pipe(Effect.scoped));
    const started = await runPromise(makeState(T3_HOME).cli([
      "thread", "start", project, "Show the file references.", "--title", name,
      "--provider", instanceId, "--model", "default", "--wait", "--json",
    ]));
    threads.push({ name, thread: JSON.parse(started.stdout) as { threadId: string } });
  }
  const results: string[][] = [];
  for (const { name, thread } of threads) {
    await t3.open(thread);
    const links = screen.getByRole("link", /^a\.ts/);
    await links.nth(1).waitFor();
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    results.push(await Promise.all([links.nth(0).textContent(), links.nth(1).textContent()]));
    await app.screenshot(name.toLowerCase().replaceAll(" ", "-"));
  }
  for (const labels of results) {
    expect(labels[0]).toContain("/one");
    expect(labels[1]).toContain("/two");
  }
});
