import { execFileSync } from "node:child_process";
import { setTimeout as delay } from "node:timers/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("An unchanged content query recovers after a slow first index", { ...WEB, timeout: 600_000, video: "off" }, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("big", { "needle.txt": "uniqueNeedleWord\n" });
  const thread = await t3.thread({ project, title: "Slow first content index", messages: ["ready"] });
  // Real files, with the same population on each commit; no finder or clock mocking.
  execFileSync("python3", ["-c", `
import os, sys
root = sys.argv[1]
for d in range(1200):
    folder = os.path.join(root, 'files', str(d))
    os.makedirs(folder, exist_ok=True)
    for f in range(1000):
        with open(os.path.join(folder, str(f) + '.txt'), 'w') as out:
            out.write('ordinary synthetic fixture content\\n')
`, project], { timeout: 240_000 });
  await t3.open(thread);
  await screen.getByTestId("composer-editor").tap();
  await app.startRecording({ name: "slow-first-content-index" });
  await browser.keyboard.press("Control+Shift+f");
  await screen.getByPlaceholder("Search in big").fill("uniqueNeedleWord");
  await delay(20_000);
  await app.screenshot("first-index-after-20-seconds");
  // Leave the query untouched for the same 2m46s observation window as triage.
  await delay(146_000);
  await app.screenshot("unchanged-query-after-166-seconds");
  const recoveredWithoutEditing = await screen.getByText("1 results in 1 files").isVisible();
  await screen.getByPlaceholder("Search in big").fill("uniqueNeedle");
  await delay(52_000);
  await app.screenshot("edited-query-after-218-seconds");
  await app.stopRecording();
  expect(recoveredWithoutEditing).toBe(true);
  await expect(screen.getByText("1 results in 1 files")).toBeVisible();
});
