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("Malformed ignore class preserves the literal file during first content search", WEB, async ({ t3, app, screen, browser }) => {
  const background = Object.fromEntries(Array.from({ length: 10000 }, (_, i) => [`background/file-${i}.txt`, "background text without the query\n".repeat(256)]));
  const project = await t3.project("ignore-search", {
    ...background,
    ".ignore": "[foo\n\\[bar\n",
    "[foo": "scoutneedle\n",
    "[bar": "scoutneedle\n",
  });
  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 === "multi-turn"));
      }),
      Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const thread = await t3.thread({ project, title: "Ignore rule search", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByTestId("composer-editor").waitFor();
  await browser.keyboard.press("Control+k");
  const palette = screen.getByRole("dialog", "Command palette");
  await palette.getByRole("combobox").fill("> Search project contents");
  await palette.getByText("Search project contents", { exact: true }).tap();
  const search = screen.getByTestId("project-content-search");
  for (const label of ["Match case", "Match whole word", "Use regular expression"]) {
    const toggle = search.getByRole("button", label, { exact: true });
    if (await toggle.getAttribute("aria-pressed") === "true") await toggle.tap();
  }
  await search.getByRole("combobox").fill("scoutneedle");
  await search.getByText(/^[01] results in [01] files$/).waitFor();
  await app.screenshot("first-content-search");
  const firstFoundFoo = await search.getByText("[foo", { exact: true }).isVisible();
  const firstFoundBar = await search.getByText("[bar", { exact: true }).isVisible();
  // Give native indexing a minute to warm before repeating the same query.
  await new Promise((resolve) => setTimeout(resolve, 60000));
  // Reload to issue a fresh RPC rather than reusing the first query's client cache.
  await t3.open(thread);
  await screen.getByTestId("composer-editor").waitFor();
  await browser.keyboard.press("Control+k");
  await palette.getByRole("combobox").fill("> Search project contents");
  await palette.getByText("Search project contents", { exact: true }).tap();
  await search.getByRole("combobox").fill("scoutneedle");
  await search.getByText(/^[01] results in [01] files$/).waitFor();
  await app.screenshot("warmed-content-search");
  await expect(search.getByText("[foo", { exact: true })).toBeVisible();
  await expect(search.getByText("[bar", { exact: true })).toHaveCount(0);
  expect(firstFoundBar).toBe(false);
  expect(firstFoundFoo).toBe(true);
});
