import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { symlinkSync, existsSync } from "node:fs";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const fixture = "http://127.0.0.1:19352";
const telemetry = async (suffix = "") => (await fetch(`${fixture}/_evidence${suffix}`)).json();

test("Gitea reuses its pull request list for subsequent no-PR branches", WEB, async ({ t3, app, browser }) => {
  const tea = `${T3_HOME}/bin/tea`;
  if (!existsSync(tea)) symlinkSync(process.env.EVIDENCE_TEA!, tea);
  const threads = [];
  const projects = [];
  for (let index = 1; index <= 3; index++) {
    const project = await t3.project(`gitea-demo-${index}`);
    projects.push(project);
    threads.push(await t3.thread({ project, title: `Gitea no-PR branch ${index}`, messages: ["Inspect this synthetic repository."] }));
  }
  for (let index = 1; index <= 3; index++) {
    const project = projects[index - 1];
    const git = (...args: string[]) => execFileSync("git", args, { cwd: project, stdio: "pipe" });
    git("remote", "add", "origin", `${fixture}/tester/demo.git`);
    git("fetch", "origin");
    git("checkout", "-B", `no-pr-branch-${index}`, `origin/no-pr-branch-${index}`);
    git("branch", "--set-upstream-to", `origin/no-pr-branch-${index}`);
  }
  await telemetry("/reset");
  await t3.open(threads[0]);
  const warm = await telemetry("/settled");
  console.log("Initial repository read:", JSON.stringify(warm));
  await telemetry("/reset");
  const measured = [];
  for (const thread of threads.slice(1)) {
    await t3.open(thread);
    const rows = await telemetry("/settled");
    measured.push(...rows);
    await telemetry("/reset");
  }
  console.log("Subsequent two no-PR branch lookups:", JSON.stringify(measured));
  // External instrumentation is labelled separately from the app; no app behavior is mocked.
  await browser.evaluate((rows) => {
    const panel = document.createElement("aside");
    panel.style.cssText = "position:fixed;z-index:2147483647;left:300px;right:24px;top:90px;padding:24px;background:#101827;color:#eef4ff;border:2px solid #6a9cff;border-radius:12px;font:16px/1.6 monospace;white-space:pre-wrap";
    panel.textContent = `EXTERNAL GITEA REQUEST MONITOR\nGitea 1.25 · tea 0.16.0 · 120 synthetic PRs\nTwo pushed branches with no PR, after initial repository read\n\n${rows.length} pull-list requests (expected at most 4)\n${rows.map((r: any) => `${r.items} items  ${r.path.replace('/api/v1/repos/tester/demo/', '')}`).join('\n')}`;
    document.body.append(panel);
  }, measured);
  await app.screenshot("gitea-request-count");
  expect(measured.length).toBeGreaterThan(0);
  expect(measured.length).toBeLessThanOrEqual(4);
});
