import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { test, WEB } from "./t3.ts";

test("Fork PR worktree preserves a local branch owning its generated prefix", WEB, async ({t3, app, screen}) => {
 const repo = await t3.project("fork-pr-demo");
 const git=(...args:string[])=>execFileSync("git",args,{cwd:repo,encoding:"utf8"}).trim();
 const parent=dirname(repo), origin=join(parent,"origin.git"), fork=join(parent,"fork.git");
 git("init","--bare",origin); git("init","--bare",fork);
 git("remote","add","origin","https://github.com/scenario/demo.git");

 git("push",origin,"main");
 git("update-ref","refs/remotes/origin/main",git("rev-parse","HEAD"));
 git("config","branch.main.remote","origin");git("config","branch.main.merge","refs/heads/main");
 git("checkout","-b","topic"); writeFileSync(join(repo,"fork.txt"),"Fork PR content\n"); git("add","fork.txt");
 git("-c","user.name=Scenario","-c","user.email=scenario@example.invalid","commit","-m","Fork change");
 git("push",fork,"topic"); const sha=git("rev-parse","HEAD");git("checkout","main");git("branch","-D","topic");
 const blocker=process.env.SCENARIO_BLOCKER ?? "t3code";
 git("branch",blocker);
 const blockerSha=git("rev-parse",blocker);
 writeFileSync(join(dirname(process.env.SCENARIO_HOSTING_SOCKET!),"fixture.json"),JSON.stringify({fork,sha}));
 await t3.open();
 await screen.getByRole("combobox").filter({hasText:"main"}).first().tap();
 await screen.getByPlaceholder("Search refs...").fill("#94");
 await screen.getByText("Checkout pull request",{exact:true}).tap();
 await screen.getByRole("button","Worktree",{exact:true}).tap();
 // Wait for checkout completion on either commit before taking the paired capture.
 await screen.getByText(/Failed to materialize pull request|t3code-pr-94-topic/).first().waitFor();
 await new Promise(resolve => setTimeout(resolve, 1000));
 let previous=await app.screenshot("settling");
 let stable=false;
 for(let attempt=1;attempt<=10;attempt++) {
   await new Promise(resolve => setTimeout(resolve, 500));
   const current=await app.screenshot("fork-pr-worktree");
   try { execFileSync("compare",["-metric","AE",previous,current,"null:"],{stdio:"pipe"}); stable=true; break; }
   catch { previous=current; }
 }
 if(!stable) throw new Error("The checkout capture did not settle.");
 console.log("Preserved user branch:",blocker,git("rev-parse",blocker)===blockerSha);
 const worktrees=git("worktree","list","--porcelain");
 for(const line of worktrees.split("\n")) {
   if(!line.startsWith("worktree ")) continue;
   const cwd=line.slice(9);
   if(cwd===repo) continue;
   const inWorktree=(...args:string[])=>execFileSync("git",args,{cwd,encoding:"utf8"}).trim();
   console.log("Created branch:",inWorktree("branch","--show-current"));
   console.log("At fork PR head:",inWorktree("rev-parse","HEAD")===sha);
   console.log("Upstream:",inWorktree("rev-parse","--abbrev-ref","@{upstream}"));
   console.log("Fork content:",inWorktree("show","HEAD:fork.txt"));
 }
 await expect(screen.getByRole("dialog")).toBeHidden();
});
