import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { ProviderInstanceId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Search snippets preserve emojis after long whitespace", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Emoji search demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const settings = yield* client["server.getSettings"]({});
    const replay = settings.providerInstances["devReplay"]!;
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("devReplay"),
      instance: { ...replay, config: { ...(replay.config as Record<string, unknown>), customModels: ["multi-turn"] } },
    } });
    yield* client["server.refreshProviders"]({ instanceId: ProviderInstanceId.make("devReplay"), fresh: true, refreshModels: true });


  }).pipe(Effect.scoped));
  const family = await t3.thread({ project, title: "Family emoji", messages: ["Start"], model: "multi-turn" });
  const flags = await t3.thread({ project, title: "Flag emojis", messages: ["Start"], model: "multi-turn" });
  for (const [thread, message] of [
    [family, `match${" ".repeat(470)}👨‍👩‍👧 rest`],
    [flags, `match${" ".repeat(474)}🇺🇸 🇫🇷 rest`],
  ] as const) {
    await t3.open(thread);
    const composer = screen.getByRole("textbox");
    await composer.fill(message);
    await composer.press("Enter");
    await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  }
  await browser.keyboard.press("Control+k");
  await screen.getByPlaceholder("Search commands, projects, and threads...").fill("match");
  await screen.getByText("In messages", { exact: true }).waitFor();
  await screen.getByText("You:", { exact: false }).first().waitFor();
  await app.screenshot("emoji-search-results");
  const dialog = screen.getByRole("dialog");
  await expect(dialog).toContainText("match 👨‍👩‍👧…");
  await expect(dialog).toContainText("match 🇺🇸…");
});
