import { readFileSync } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Nightly does not offer an update to the latest Stable desktop", WEB, async ({ t3, app, screen, browser }) => {
  const capture = async (label: string) => {
    let previous = readFileSync(await app.screenshot(`${label}-settling`));
    for (let i = 0; i < 20; i++) {
      await delay(500);
      const current = readFileSync(await app.screenshot(`${label}-settling`));
      if (previous.equals(current)) { await app.screenshot(label); return; }
      previous = current;
    }
    throw new Error(`Screen did not settle: ${label}`);
  };
  await t3.project("Update proof");
  await t3.open("/settings/connections");
  const output = execFileSync(process.env.STABLE_LAUNCHER!, ["pair", "--base-dir", process.env.STABLE_T3_HOME!, "--ttl", "10m"], { env: { ...process.env, HOME: process.env.STABLE_HOME!, T3CODE_HOME: process.env.STABLE_T3_HOME! }, encoding: "utf8" });
  const pairing = output.match(/Pairing URL: (http\S+)/)![1];
  await screen.getByRole("button", "Add environment").tap();
  await browser.evaluate(() => { const style = document.createElement('style'); style.textContent = 'input { -webkit-text-security: disc !important; }'; document.head.appendChild(style); });
  await screen.getByPlaceholder("backend.example.com").fill(pairing);
  await screen.getByRole("dialog").getByRole("button", "Add environment").tap();
  await screen.getByText("Connected · 0.1.9", { exact: false }).waitFor({ state: "visible", timeout: 60000 });
  await screen.getByRole("dialog", "Add environment").waitFor({ state: "hidden" });
  await screen.getByText("Backend added", { exact: true }).waitFor({ state: "hidden", timeout: 30000 });
  await capture("environments-update-offer");
  await t3.open();
  await capture("sidebar-update-offer");
  const offer = screen.getByRole("button", "Update 1 server");
  if (await offer.count()) {
    await offer.tap();
    await screen.getByText("Checking for more…", { exact: false }).waitFor({ state: "hidden", timeout: 60000 });
    await capture("update-confirmation");
  } else {
    await capture("update-confirmation");
  }
  await expect(screen.getByRole("heading", "Update 1 machine?")).not.toBeVisible();
  await expect(offer).not.toBeVisible();
});
