import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { ProviderInstanceId } from "@t3tools/contracts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

test("Find searches the BOM-prefixed list exactly like the BOM-free list", WEB, async ({ t3, app, screen, browser }) => {
  // Supply the reported synthetic response through the app's Replay (dev) agent.
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const replay = (text: string) => [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", 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") + "\n";
  try {
    const project = await t3.project("List search");
    const { origin } = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
    const catalog = await runPromise(Effect.scoped(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, origin);
      return yield* client["server.refreshProviders"]({ instanceId: ProviderInstanceId.make("devReplay"), cwd: project, fresh: true, refreshModels: true });
    })));
    await writeFile(fixture, replay("\uFEFF-     \tfoo\n          bar"));
    const replayProvider = catalog.providers.find((provider) => provider.instanceId === "devReplay")!;
    const model = replayProvider.models.some((model) => model.slug === "showcase") ? "showcase" : "default";
    const bom = await t3.thread({ project, title: "BOM-prefixed list", model, messages: ["show the list"] });
    await writeFile(fixture, replay("-     \tfoo\n          bar"));
    const control = await t3.thread({ project, title: "BOM-free list", model, messages: ["show the list"] });
    const search = async (thread: typeof bom, label: string) => {
      await t3.open(thread);
      await screen.getByText("foo bar", { exact: true }).waitFor();
      await browser.keyboard.press("Control+f");
      await screen.getByRole("searchbox", "Find in thread").fill("foo bar");
      try {
        await expect.poll(() => browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""'), { message: "Find returns one occurrence of foo bar" }).toBe("1/1");
        await expect.poll(() => browser.evaluate<number>('(CSS.highlights.get("t3-thread-find-active")?.size ?? 0)'), { message: "Find highlights the matching reply" }).toBe(1);
      } finally {
        await app.screenshot(label);
      }
    };
    await search(control, "bom-free-control");
    await search(bom, "bom-prefixed-find");
  } finally {
    await writeFile(fixture, original);
  }
});
