/// <reference lib="dom" />
import { expect } from "e2e";
import { spawn } from "node:child_process";
import { mkdir, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { startSecondServer } from "./second-server.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const fixtureRoot = process.env.PROOF_FIXTURE_ROOT!;
async function oldServer(origin: string, suffix: string, port = 0) {
  if (!port) {
    const socket = createServer();
    await new Promise<void>((resolve) => socket.listen(0, "127.0.0.1", resolve));
    port = (socket.address() as { port: number }).port;
    await new Promise<void>((resolve) => socket.close(() => resolve()));
  }
  const home = `${T3_HOME}-remote-${suffix}-${Date.now()}`;
  await mkdir(`${home}/userdata`, { recursive: true });
  await mkdir(`${home}/bin`, { recursive: true });
  await writeFile(`${home}/bin/hostnamectl`, "#!/bin/sh\nprintf 'Remote B\\n'\n", { mode: 0o755 });
  await writeFile(`${home}/userdata/settings.json`, JSON.stringify({ providerInstances: Object.fromEntries(["codex", "claudeAgent", "cursor", "grok", "muse", "pi", "opencode", "antigravity"].map(driver => [driver, { driver, enabled: false }])) }));
  const child = spawn(`${fixtureRoot}/remote-runtime/t3`, ["serve", "--host", "127.0.0.1", "--port", String(port), "--base-dir", home, "--dev-url", origin], { env: { PATH: `${home}/bin:${process.env.PATH}`, HOME: process.env.HOME, T3CODE_DEV_SEED: "0", T3CODE_ENVIRONMENT_LABEL: "Remote B", T3CODE_ENVIRONMENT_MACHINE_KIND: "laptop", T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0" }, stdio: ["ignore", "pipe", "pipe"] });
  let output = "";
  const token = await new Promise<string>((resolve, reject) => {
    child.stdout.on("data", data => { output += data.toString(); const match = /Token:\s*(\S+)/.exec(output); if (match) resolve(match[1]!); });
    child.stderr.on("data", data => { output += data.toString(); });
    child.once("exit", code => reject(new Error(`Remote startup exited ${code}: ${output.slice(-1200)}`)));
  });
  return { host: `http://127.0.0.1:${port}`, port, token, stop: async () => { if (child.exitCode !== null) return; const exit = new Promise<void>(resolve => child.once("exit", () => resolve())); child.kill("SIGTERM"); await exit; } };
}

test("The update dialog explains disabled and failed saved connections", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1440, height: 900 });
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Update review", messages: ["first"] });
  const origin = app.baseUrl ?? "";
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    yield* client["server.updateSettings"]({ patch: { providerInstances: { codex: { driver: "codex", enabled: true, config: { binaryPath: `${fixtureRoot}/provider/bin/codex` } } } } });
    yield* client["server.refreshProviders"]({ fresh: true, refreshModels: true });
  }).pipe(Effect.scoped));
  const a = startSecondServer(origin);
  let b = await oldServer(origin, "original");
  const pair = async (host: string, token: string) => {
    await screen.getByRole("button", "Add environment", { exact: true }).tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment", { exact: true }).tap();
  };
  const openSettings = async () => {
    await screen.getByRole("button", "Settings", { exact: true }).tap();
    await screen.getByRole("button", "Environments", { exact: true }).tap();
    await screen.getByRole("button", "List", { exact: true }).tap();
  };
  const closeSettings = () => screen.getByRole("dialog", "Settings", { exact: true }).getByRole("button", "Close", { exact: true }).tap();
  const updateButton = () => screen.getByRole("button", "Update 1 provider", { exact: true });
  const openUpdate = async () => {
    await updateButton().tap({ timeout: 60000 });
    await screen.getByText("Checking for more…", { exact: false }).waitFor({ state: "hidden", timeout: 60000 });
    await screen.getByRole("button", "1 skipped", { exact: true }).tap();
    await screen.getByText("Remote B", { exact: true }).waitFor();
    await browser.evaluate(async () => { await Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {}))); });
  };
  try {
    const ar = await a.ready;
    await t3.open(thread);
    await openSettings();
    await pair(ar.host, ar.token);
    await screen.getByRole("switch", "Switch off Scenario").waitFor({ timeout: 60000 });
    await pair(b.host, b.token);
    await screen.getByRole("switch", "Switch off Remote B").waitFor({ timeout: 60000 });
    await closeSettings();
    await openUpdate();
    await app.screenshot("connected-manual-update-baseline");
    await screen.getByRole("button", "Cancel", { exact: true }).tap();
    await openSettings();
    await screen.getByRole("switch", "Switch off Scenario").uncheck();
    await screen.getByRole("switch", "Switch off Remote B").uncheck();
    await app.screenshot("settings-both-off");
    await closeSettings();
    await openUpdate();
    const disabledText = await browser.locator('[role="alertdialog"]').textContent();
    await app.screenshot("turned-off-skipped");
    await screen.getByRole("button", "Cancel", { exact: true }).tap();
    await openSettings();
    await screen.getByRole("switch", "Switch on Remote B").check();
    await screen.getByRole("switch", "Switch off Remote B").waitFor();
    await b.stop();
    await screen.getByText("did not answer", { exact: false }).first().waitFor({ timeout: 60000 });
    await closeSettings();
    await openUpdate();
    const failedText = await browser.locator('[role="alertdialog"]').textContent();
    await app.screenshot("stopped-server-skipped");
    await screen.getByRole("button", "Cancel", { exact: true }).tap();
    b = await oldServer(origin, "replacement", b.port);
    await openSettings();
    await screen.getByRole("switch", "Switch off Remote B").uncheck();
    await screen.getByRole("switch", "Switch on Remote B").check();
    await screen.getByText("did not answer", { exact: false }).first().waitFor({ timeout: 60000 });
    await screen.getByRole("button", "Details", { exact: true }).tap();
    await browser.locator('dd:has-text("Connected environment"), dd:has-text("different T3 Code install")').waitFor({ timeout: 60000 });
    await app.screenshot("settings-different-installation");
    await closeSettings();
    await openUpdate();
    const mismatchText = await browser.locator('[role="alertdialog"]').textContent();
    await app.screenshot("different-installation-skipped");
    expect(disabledText).toContain("turned off");
    expect(failedText).not.toContain("not connected");
    expect(mismatchText).toContain("Remove this connection and add it again.");
  } finally { await b.stop(); await a.stop(); }
});
