import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Literal trailing spaces keep distinct file labels and searchable folders", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("file links");
  const literal = "[first](</tmp/one/a.ts >) and [second](</tmp/two/a.ts >)";
  const encoded = "[first](/tmp/one/a.ts%20) and [second](/tmp/two/a.ts%20)";
  const transcript = join(T3_HOME, "literal-links.ndjson");
  const frames = [literal, encoded].flatMap(text => [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ]);
  writeFileSync(transcript, frames.map(frame => JSON.stringify(frame)).join("\n") + "\n");
  // Use the app's real replay agent, with the exact two synthetic replies from the report.
  const replay = join(T3_HOME, "literal-links-replay.ts");
  const source = readFileSync(join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"), "utf8");
  writeFileSync(replay, source.replace(/export const SCENARIOS = \[[\s\S]*?\] as const;/, `export const SCENARIOS = ${JSON.stringify([{ id: "repro", name: "Literal links", file: pathToFileURL(transcript).href }])} as const;`));
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("devReplay"), instance: {
        driver: ProviderDriverKind.make("acpRegistry"), displayName: "Replay (dev)", enabled: true,
        config: { source: "local", commandPath: process.execPath, commandArgs: [replay] },
      },
    } });
    yield* client.subscribeServerConfig({}).pipe(Stream.filter(event => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some(provider => provider.instanceId === "devReplay" && provider.models?.some(model => model.slug === "repro"));
    }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("60 seconds")));
  const thread = await t3.thread({ project, title: "literal spaces and encoded control", model: "repro", messages: ["Show the literal-space file links", "Show the percent-encoded control"] });
  await t3.open(thread);
  await screen.getByRole("link", /^a\.ts/).first().waitFor();
  await app.screenshot("literal-and-percent-encoded-links");
  const results: string[] = [];
  await browser.keyboard.press("Control+f");
  for (const folder of ["tmp/one", "tmp/two"]) {
    await screen.getByRole("searchbox", "Find in thread").fill(folder);
    await browser.locator('[data-thread-find-bar] [role="search"][aria-busy="false"]').waitFor();
    await expect.poll(() => browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""')).toMatch(/^1\/[12]$/);
    await app.screenshot(folder === "tmp/one" ? "find-one" : "find-two");
    results.push(await browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""'));
  }
  await expect(results).toEqual(["1/2", "1/2"]);
  await expect(screen.getByRole("link", "a.ts · tmp/one", { exact: true })).toHaveCount(2);
  await expect(screen.getByRole("link", "a.ts · tmp/two", { exact: true })).toHaveCount(2);
});
