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

test("Message search preserves vowel signs and highlights remaining combining accents", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Search proof");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    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 === "command-output"));
      }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const a = await t3.thread({ project, title: "Replay: command-output", messages: ["Start"], model: "command-output" });
  const b = await t3.thread({ project, title: "Replay: command-output", messages: ["Start"], model: "command-output" });
  async function send(text: string) {
    await screen.getByRole("textbox").fill(text);
    await screen.getByRole("textbox").press("Enter");
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
    await screen.getByRole("button", "Submit message").waitFor();
  }
  await t3.open(a);
  await send("बातचीत अबत");
  await send("กินข้าว อกน");
  await send("try eko sale");
  await send("привет мир");
  await send("cafe resume");
  await t3.open(b);
  await send("बत करो बातचीत");
  await browser.keyboard.press("Control+k");
  const observations: Array<{label: string; text: string; highlights: string[]}> = [];
  for (const [label, query] of [
    ["001-hindi-control", "बातचीत"],
    ["002-hindi-prefix", "बात"],
    ["003-thai-control", "กินข้าว"],
    ["004-thai-prefix", "กิน"],
    ["005-exact-phrase", '"बात करो"'],
    ["006-latin-combining-accent", "ẹ́ko"],
    ["007-cyrillic-combining-accent", "приве́т"],
    ["008-quoted-combining-accent", '"ẹ́ko sale"'],
    ["009-latin-nfc-control", "café resumé"],
  ]) {
    await browser.locator('[role="dialog"] [role="combobox"]').fill(query!);
    // Allow the palette's debounce and server search to finish before recording its visible result.
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 1500)));
    await app.screenshot(label!);
    const result = await browser.evaluate(() => {
      const dialog = document.querySelector('[role="dialog"]')!;
      return {text: dialog.textContent ?? "", highlights: Array.from(dialog.querySelectorAll("mark")).map(e => e.textContent ?? "")};
    });
    observations.push({label: label!, ...result});
  }
  const get = (label: string) => observations.find(o => o.label.includes(label))!;
  expect(get("002").text).toContain("बातचीत अबत");
  expect(get("004").text).toContain("กินข้าว อกน");
  expect(get("005").text).not.toContain("बत करो बातचीत");
  expect(get("006").highlights.join(" ")).toContain("eko");
  expect(get("007").highlights.join(" ")).toContain("привет");
  expect(get("008").highlights.join(" ")).toContain("eko sale");
});
