/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { renameSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const traceFile = process.env.GIT_TRACE2_EVENT!;
async function grepExitAfter(offset: number) {
  for (let i = 0; i < 1500; i++) {
    const events = readFileSync(traceFile, "utf8").slice(offset).split("\n").flatMap(line => {
      try { return [JSON.parse(line)]; } catch { return []; }
    });
    const start = events.find(e => e.event === "start" && e.argv?.includes("grep"));
    const exit = start && events.find(e => e.event === "exit" && e.sid === start.sid);
    if (exit) return { argv: start.argv, start: start.time, exit: exit.time, code: exit.code, duration: exit.t_abs };
    await delay(20);
  }
  throw new Error("The app's git grep did not exit in 30 seconds");
}

test("Content search during indexing ignores user git output and recursion settings", WEB, async ({ t3, app, screen, browser }) => {
  const observations: unknown[] = [];
  let recursiveAfterGit = "";
  let regexHighlights: (string | null)[] = [];
  for (const mode of ["recursive", "literal", "regex"] as const) {
    const project = await t3.project(`project-${mode}`, { "src/a.ts": "const needle = 1;\n" });
    const root = dirname(project);
    renameSync(join(project, ".git"), join(root, ".git"));
    const git = (...args: string[]) => execFileSync("git", args, { cwd: root });
    git("add", "-A");
    git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qm", "Nested project");
    git("config", "grep.column", "true");
    git("config", "grep.fullName", "true");
    git("config", "submodule.recurse", mode === "recursive" ? "true" : "false");
    // Real text files keep the native content index warming up, like a large checkout.
    execFileSync("python3", ["-c", `import os,sys\np=sys.argv[1]\nfor d in range(150):\n q=os.path.join(p,'filler',str(d));os.makedirs(q,exist_ok=True)\n for n in range(1000):\n  with open(os.path.join(q,str(n)+'.txt'),'w') as f:f.write('unrelated filler text abcdefghijklmnopqrstuvwxyz 0123456789\\n'*64)`, project]);
    if (mode === "recursive") git("add", "-A");
    const thread = await t3.thread({ project, title: `Git config: ${mode}`, messages: ["Ready for content search"] });
    await t3.open(thread);
    await screen.getByRole("textbox", `Message Git config: ${mode}`, { exact: true }).waitFor();
    await browser.keyboard.press("Control+Shift+f");
    const input = screen.getByPlaceholder(`Search in project-${mode}`);
    await input.waitFor();
    if (mode === "regex") await screen.getByRole("button", "Use regular expression", { exact: true }).tap();
    const traceOffset = readFileSync(traceFile, "utf8").length;
    await input.fill(mode === "regex" ? "ne+dle" : "needle");
    if (mode === "recursive") {
      const gitExit = await grepExitAfter(traceOffset);
      await delay(150);
      recursiveAfterGit = await browser.evaluate(() => document.querySelector('[data-testid="project-content-search"]')?.textContent ?? "");
      observations.push({ mode, afterGitExit: { gitExit, text: recursiveAfterGit } });
      await app.screenshot("recursive-fallback-exited");
    }
    await delay(3000);
    await app.screenshot(`${mode}-03-seconds`);
    const snapshot = () => browser.evaluate(() => {
      const dialog = document.querySelector('[data-testid="project-content-search"]');
      return { text: dialog?.textContent ?? document.body.innerText, highlights: Array.from(dialog?.querySelectorAll('mark') ?? []).map(x => x.textContent) };
    });
    const at3 = await snapshot();
    observations.push({ mode, at3Seconds: at3 });
    if (mode === "regex") regexHighlights = at3.highlights;
    if (mode === "recursive") {
      await delay(7000);
      await app.screenshot("recursive-10-seconds");
      observations.push({ mode, at10Seconds: await snapshot() });
    }
    await screen.getByText("a.ts", { exact: true }).waitFor();
    await app.screenshot(`${mode}-result`);
    observations.push({ mode, result: await snapshot() });
    await browser.keyboard.press("Escape");
  }
  const text = JSON.stringify(observations);
  console.log("SEARCH_OBSERVATIONS", text);
  expect(recursiveAfterGit).not.toContain("Searching");
  expect(recursiveAfterGit).toContain("const needle = 1;");
  expect(regexHighlights).toEqual(["needle"]);
  expect(text).not.toContain("7\\u0000");
  expect(text).not.toContain("project-literal/src");
  expect(text).not.toContain("project-regex/src");
});
