import { expect } from "e2e";
import fs from "node:fs";
import path from "node:path";
import { test, WEB, runPromise } from "./t3.ts";
import { run } from "./shell.ts";
import { APP_DIR } from "../e2e.config.ts";

test("Device setup explains a missing npm and keeps the host failure after Retry", WEB, async ({ t3, app, screen }) => {
  const stableCapture = async (label: string) => {
    let previous = await app.screenshot(label + "-stability");
    for (let attempt = 0; attempt < 10; attempt++) {
      await new Promise((resolve) => setTimeout(resolve, 500));
      const next = await app.screenshot(label);
      const read = (file: string) => fs.readFileSync(path.resolve(file));
      if (read(previous).equals(read(next))) return;
      previous = next;
    }
    throw Error("The capture did not settle");
  };
  const project = await t3.project("device-setup");
  await t3.open();
  await screen.getByRole("textbox").fill("Check device setup");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("This turn is a replay.", { exact: false }).waitFor();
  await screen.getByRole("button", "Stop generation").waitFor({state: "hidden", timeout: 90000});
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByText("Device", { exact: true }).last().tap();
  await stableCapture("before-enable");
  await app.startRecording();
  await screen.getByRole("switch", "Enable device hub").tap();
  await screen.getByRole("button", "Retry", { exact: true }).waitFor();
  await stableCapture("setup-failure");
  await screen.getByRole("button", "Retry", { exact: true }).tap();
  await screen.getByRole("button", "Retry", { exact: true }).waitFor();
  await stableCapture("retry-failure");
  await app.stopRecording();
  const setupText = await screen.getByRole("dialog", "Set up devices").textContent();
  await screen.getByRole("button", "Close", {exact: true}).tap();
  await screen.getByRole("textbox").fill("Inspect the unavailable device host");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByRole("button", "Stop generation").waitFor();
  await runPromise(run(process.execPath, ["/tmp/device-setup-proof/call-device-tools.mjs"], {cwd: APP_DIR}));
  await expect(setupText).toContain("Device support needs npm, which is not on the T3 server's PATH.");
  await expect(setupText).toContain("Install npm (it comes with Node.js from nodejs.org), restart T3 Code, then retry.");
});
