import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Installed hosting CLIs report probe failures rather than installation advice", WEB, async ({ t3, app, screen, browser }) => {
  // start-app puts this isolated home's bin first on the real server's PATH.
  const shim = async (name: string, body: string) =>
    writeFile(join(T3_HOME, "bin", name), `#!/bin/sh\n${body}\n`, { mode: 0o755 });
  await shim("gh", 'sleep 10\nexec /usr/bin/gh "$@"');
  await shim("fj", 'sleep 10\nexit 0');
  await t3.project("CLI probe demo");
  await t3.open();
  await screen.getByRole("button", "Add project").waitFor({ state: "visible", timeout: 60000 });
  await app.open("/settings/source-control");
  const ready = browser.locator('button[aria-label="Rescan server environment"]:not(:disabled)');
  await ready.waitFor({ state: "visible", timeout: 60000 });
  await screen.getByRole("button", "Rescan server environment").tap();
  await ready.waitFor({ state: "visible", timeout: 60000 });
  await browser.evaluate(() => {
    const heading = [...document.querySelectorAll("h2")].find((node) => node.textContent?.trim() === "Source control providers");
    heading?.scrollIntoView({ block: "start", behavior: "instant" });
  });
  await app.screenshot("slow-gh-and-fj-probe");
  const timeoutText = await browser.evaluate(() => document.body.innerText);
  await shim("gh", "exit 1");
  await screen.getByRole("button", "Rescan server environment").tap();
  await ready.waitFor({ state: "visible", timeout: 60000 });
  await browser.evaluate(() => {
    const heading = [...document.querySelectorAll("h2")].find((node) => node.textContent?.trim() === "Source control providers");
    heading?.scrollIntoView({ block: "start", behavior: "instant" });
  });
  await app.screenshot("gh-exit-status");
  const exitText = await browser.evaluate(() => document.body.innerText);
  expect(timeoutText).toContain("`gh --version` timed out after 5000ms");
  expect(timeoutText).toContain("`fj version` timed out after 5000ms");
  expect(timeoutText).toContain("server's PATH resolves");
  expect(exitText).toContain("`gh --version` exited with status 1");
});
