import { chmod, readFile, writeFile, watch } from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

const untilFile = async (file: string) => {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 45000);
  try {
    const events = watch(file.slice(0, file.lastIndexOf('/')), { signal: controller.signal });
    for await (const _event of events) {
      try { await readFile(file); return; } catch {}
    }
  } finally { clearTimeout(timer); controller.abort(); }
};

test("Refreshing a merge request leaves a branch switched in during fetch alone", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo", { "t3.json": JSON.stringify({defaultThreadEnvMode:"local"}) });
  const git = (...args: string[]) => runPromise(run("/usr/bin/git", args, {cwd:project}));
  await git("remote", "add", "origin", "https://gitlab.com/julius54/refresh-proof-47502-20261202.git");
  await git("fetch", "origin", "main", "review-source");
  await git("reset", "--hard", "origin/main");
  await git("branch", "review-source", "main");
  await git("branch", "separate-work", "main");
  const original = (await git("rev-parse", "main")).stdout.trim();
  const worktree = `${project}-review`;
  await git("worktree", "add", worktree, "review-source");
  const gate = `${T3_HOME}/fetch-gate`;
  const shim = `${T3_HOME}/bin/git`;
  // This schedules the race; it forwards all commands to the installed Git and real GitLab.
  await writeFile(shim, `#!/usr/bin/env node\nimport fs from 'node:fs';import cp from 'node:child_process';\nconst args=process.argv.slice(2);\nif(args.includes('fetch') && fs.existsSync(${JSON.stringify(gate+'-armed')})){fs.unlinkSync(${JSON.stringify(gate+'-armed')});fs.writeFileSync(${JSON.stringify(gate+'-started')},'fetch pending');const wait=new Int32Array(new SharedArrayBuffer(4));while(!fs.existsSync(${JSON.stringify(gate+'-release')}))Atomics.wait(wait,0,0,50);}\nconst r=cp.spawnSync('/usr/bin/git',args,{stdio:'inherit'});process.exit(r.status??1);\n`);
  await chmod(shim, 0o755);
  const thread = await t3.thread({project,title:"Review refresh race",messages:["Review the change"]});
  await browser.setViewport({width:1280,height:800});
  await t3.open(thread);
  await screen.getByRole("button", "New thread", {exact:true}).tap();
  const branch = browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first();
  await branch.click();
  await screen.getByPlaceholder("Search refs...").fill("#1");
  const checkout = /Checkout (?:merge|pull|change) request/i;
  await screen.getByRole("option",checkout).tap();
  const dialog=screen.getByRole("dialog",checkout);
  await dialog.getByText("Changes for review",{exact:true}).waitFor();
  await writeFile(gate+'-armed','armed');
  const started=untilFile(gate+'-started');
  await dialog.getByRole("button","Worktree",{exact:true}).tap();
  await started;
  await runPromise(run('/usr/bin/git',['switch','separate-work'],{cwd:worktree}));
  await writeFile(gate+'-release','release');
  await dialog.waitFor({state:'hidden'});
  await screen.getByRole("button","Toggle terminal drawer").tap();
  const input=screen.getByRole("textbox","Terminal input");
  await input.waitFor();
  await input.focus();
  const printed=untilFile(`${worktree}/proof-printed`);
  await browser.keyboard.type("PS1='demo $ '; clear; printf 'Branch after refresh: '; git branch --show-current; printf 'separate-work commit: '; git rev-parse --short separate-work; printf 'Expected original: '; git rev-parse --short main; printf 'file.txt: '; cat file.txt; touch proof-printed\n");
  await printed;
  const current=(await runPromise(run('/usr/bin/git',['rev-parse','separate-work'],{cwd:worktree}))).stdout.trim();
  const contents=await readFile(`${worktree}/file.txt`,'utf8');
  await app.screenshot("branch-after-refresh");
  expect({commit:current,contents}).toEqual({commit:original,contents:'original\n'});
});
