import * as fs from "node:fs/promises";
import * as path from "node:path";
import { execFileSync, spawn } from "node:child_process";
import { once } from "node:events";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

// The companion forge.py serves synthetic GitHub responses over gh's supported Unix socket.
// model.py supplies a deterministic guide through the real Codex text-generation subprocess.
const root = process.env.REVIEW_FIXTURE_DIR!;

test("A rewritten guide shows the new push even after Code refreshes", WEB, async ({t3, app, browser, screen}) => {
  const forge = spawn("python3", [path.join(root,"forge.py"),root], {stdio:["ignore","pipe","pipe"]});
  await Promise.race([once(forge.stdout!,"data"),once(forge,"error").then(([error])=>Promise.reject(error))]);
  try {
  await browser.emulateMedia({colorScheme: "dark"});
  const project = await t3.project("Greeting review", {
    "greeting.ts": 'export const greeting = "BASE_GREETING";\n',
    ".git/config": `[remote "origin"]\n\turl = git@GitHub.com:scenario/review-guide.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n[core]\n\tsshCommand = ${path.join(root, "ssh.py")}\n`,
  });
  const git = (...args: string[]) => execFileSync("git",args,{cwd:project,encoding:"utf8"}).trim();
  const commit = () => {git("add","greeting.ts"); git("-c","user.name=Scenario","-c","user.email=scenario@example.invalid","commit","--quiet","-m","Update greeting");return git("rev-parse","HEAD");};
  const base=git("rev-parse","HEAD");
  git("checkout","--quiet","-b","greeting");
  await fs.writeFile(path.join(project,"greeting.ts"),'export const greeting = "PREVIOUS_PUSH";\n');
  let head=commit();
  const publish=() => fs.writeFile(path.join(root,"state.json"),JSON.stringify({workspace:project,base,head}));
  await publish();
  const thread=await t3.thread({project,title:"Review greeting",messages:["Prepare the greeting review"]});
  const settingsPath=path.join(T3_HOME,"userdata/settings.json");
  const settings=JSON.parse(await fs.readFile(settingsPath,"utf8"));
  settings.reviewGuidesEnabled=true;
  settings.reviewGuideModelSelection={instanceId:"codex",model:"fixture"};
  settings.providerInstances.codex={driver:"codex",enabled:true,config:{binaryPath:path.join(root,"model.py"),homePath:path.join(root,"codex-home"),customModels:["fixture"]}};
  await fs.writeFile(settingsPath,JSON.stringify(settings));
  await t3.open("/pull-requests?repository=scenario%2Freview-guide&number=1&selectedHost=github.com");
  await screen.getByRole("button","Guide",{exact:true}).tap();
  await screen.getByRole("button","Write guide",{exact:true}).tap();
  await screen.getByText("Read the greeting",{exact:true}).last().waitFor({state:"visible",timeout:90000});
  await screen.getByText(/PREVIOUS_PUSH/).first().waitFor({state:"visible",timeout:60000});
  await app.screenshot("original-guide");
  await fs.writeFile(path.join(project,"greeting.ts"),'export const greeting = "CURRENT_PUSH";\n');
  head=commit(); await publish();
  // The app remains mounted, keeping the previous push's query pages in the client registry.
  await screen.getByRole("button","More pull request actions",{exact:true}).tap();
  await screen.getByRole("menuitem","Refresh",{exact:true}).tap();
  await screen.getByRole("button","Rewrite",{exact:true}).tap();
  await screen.getByText("Rewriting this guide. You will be told when the new one is ready.",{exact:true}).waitFor({state:"hidden",timeout:90000});
  await app.screenshot("rewritten-guide");
  await screen.getByRole("button","Code",{exact:true}).tap();
  await screen.getByRole("button","More pull request actions",{exact:true}).tap();
  await screen.getByRole("menuitem","Refresh",{exact:true}).tap();
  await screen.getByRole("button","Expand all files",{exact:true}).tap();
  await screen.getByText(/CURRENT_PUSH/).first().waitFor({state:"visible",timeout:60000});
  await app.screenshot("refreshed-code");
  await screen.getByRole("button","Guide",{exact:true}).tap();
  await screen.getByText("Read the greeting",{exact:true}).last().waitFor({state:"visible"});
  await app.screenshot("guide-after-code-refresh");
  await expect(browser.locator('[aria-keyshortcuts="J K"]').getByText(/CURRENT_PUSH/).first()).toBeVisible();
  await expect(browser.locator('[aria-keyshortcuts="J K"]').getByText(/PREVIOUS_PUSH/).first()).not.toBeVisible();
  } finally {
    const stopped=once(forge,"exit");
    forge.kill("SIGTERM");
    await stopped;
  }
});
