import { execFileSync, execFile } from "node:child_process";
import { promisify } from "node:util";
import { readFileSync, mkdirSync, writeFileSync } from "node:fs";
import { DatabaseSync } from "node:sqlite";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
async function waitFor<A>(read: () => A | undefined, label: string, ms=150000): Promise<A> {
  const end = Date.now()+ms;
  while (Date.now()<end) { const value=read(); if(value!==undefined) return value; await pause(500); }
  throw new Error(`Timed out: ${label}`);
}

test("New pull requests behind a busy first page both start runs", WEB, async ({t3, app, screen}) => {
  const seed=await waitFor(()=>{ const value=JSON.parse(readFileSync(process.env.PROOF_SEED_FILE!,"utf8")); return value.busy?value:undefined; },"real GitLab seed",650000);
  const project=await t3.project("Pagination proof");
  for (const kind of ["quiet","busy"]) {
    const cwd=`${project}/${kind}`;mkdirSync(cwd);
    execFileSync("git",["init","--quiet","--initial-branch=main"],{cwd});
    execFileSync("git",["remote","add","origin",seed[kind].url],{cwd});
  }
  const settings=(enabled:boolean)=>runPromise(Effect.gen(function*(){
    const client=yield* rpcClient(T3_HOME,app.baseUrl!);
    yield* client["server.updateSettings"]({patch:{workflowsEnabled:enabled}});
  }).pipe(Effect.scoped));
  const db=new DatabaseSync(`${T3_HOME}/userdata/statev2.sqlite`,{readOnly:true});
  try {
    mkdirSync(`${T3_HOME}/workflows`,{recursive:true});
    writeFileSync(`${T3_HOME}/workflows/newpr.ts`,`export default T3.workflow("newpr", {
      version: 1, payload: T3.PullRequest,
      triggers: [T3.pullRequests.opened({project:${JSON.stringify(project)}})]
    }, Effect.fn(function* (pr) {
      yield* T3.title(pr.title);
      yield* T3.subject(pr);
      return "Started automatically for newly opened merge request";
    }));`);
    await settings(true);
    await waitFor(()=>db.prepare("SELECT next_at FROM workflow_triggers").get(),"initial trigger watermark");
    await settings(false);
    await t3.open("/workflows");
    const {stdout}=await promisify(execFile)("python3",[process.env.PROOF_DRIVER!,"round"],{timeout:650000});
    const round=JSON.parse(stdout);
    if(round.x.position<=100 || round.y.position>100) throw new Error("Real GitLab listing did not bury X on page 2");
    console.log("Real GitLab ordering",round);
    await settings(true);
    // Observe the real poll advancing through Y, then let the following poll try again.
    await waitFor(()=>{
      const row=db.prepare("SELECT next_at FROM workflow_triggers").get() as {next_at:string}|undefined;
      return row && Date.parse(row.next_at)>=Math.floor(Date.parse(round.y.createdAt)/1000)*1000?row:undefined;
    },"poll watermark advanced past both new MRs");
    await pause(70000);
    await t3.open("/workflows");
    await screen.getByRole("button","All runs",{exact:true}).waitFor();
    await app.screenshot("new-pr-runs-after-two-polls");
    const titles=db.prepare("SELECT title FROM workflow_runs WHERE workflow='newpr' ORDER BY title").all().map(row=>row.title);
    console.log("Runs after two real polls",titles);
    await expect(titles).toEqual(["X buried new work","Y visible new work"]);
  } finally { await settings(false);db.close(); }
});
