import { expect } from "e2e";
import { writeFile, symlink } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { setTimeout } from "node:timers/promises";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Rescan discovers gh added to the login-shell PATH while the server remains running", WEB,
  async ({ t3, app, screen, browser }) => {
    await t3.project("Rescan demonstration");
    await t3.open();
    await screen.getByRole("button", "Settings", { exact: true }).tap();
    await app.open("/settings/source-control");
    await screen.getByRole("button", "Rescan server environment").tap();
    await setTimeout(2000);
    await browser.evaluate(() => document.querySelector('[aria-label="GitHub availability"]')?.scrollIntoView({ block: "center" }));
    await setTimeout(500);
    await app.screenshot("before-install");
    const root = process.env.RESCAN_FIXTURE_ROOT!;
    await symlink("/usr/bin/gh", `${root}/installed-bin/gh`).catch((error) => {
      if (error.code !== "EEXIST") throw error;
    });
    await writeFile(`${T3_HOME}/login-profile`, `export PATH="${root}/installed-bin:$PATH"\n`);
    const output = execFileSync(process.env.SHELL!, ["-ilc", "command -v gh; gh --version"], { encoding: "utf8" });
    console.log("Fresh login shell finds the installed GitHub CLI:", output.split("\n").filter(line => line.startsWith("gh version")).join("\n"));
    // Discovery caches its shell refresh for ten seconds.
    await setTimeout(11000);
    await screen.getByRole("button", "Rescan server environment").tap();
    await setTimeout(3000);
    await browser.evaluate(() => document.querySelector('[aria-label="GitHub availability"]')?.scrollIntoView({ block: "center" }));
    await setTimeout(500);
    await app.screenshot("after-rescan");
    await expect(screen.getByText("gh version 2.97.0 (2026-07-31)", { exact: false })).toBeVisible();
  });
