import { spawn } from "node:child_process";
import { createServer } from "node:net";
import { createInterface } from "node:readline";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { prepareHome } from "./start-app.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

async function machine(name: string, devUrl: string) {
  const home = `${T3_HOME}/proof-machines/${name}`;
  await runPromise(prepareHome(home));
  const port = await new Promise<number>((resolve) => {
    const socket = createServer();
    socket.listen(0, "127.0.0.1", () => {
      const address = socket.address() as { port: number };
      socket.close(() => resolve(address.port));
    });
  });
  const child = spawn(process.execPath, ["apps/server/src/bin.ts", "serve", "--host", "127.0.0.1", "--port", String(port), "--base-dir", home, "--dev-url", devUrl], {
    cwd: APP_DIR,
    env: { PATH: process.env.PATH, HOME: process.env.HOME, T3CODE_DEV_SEED: "0", T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0", T3CODE_ENVIRONMENT_LABEL: name, T3CODE_ENVIRONMENT_MACHINE_KIND: "server" },
    stdio: ["ignore", "pipe", "pipe"],
  });
  const exit = new Promise<void>((resolve) => child.once("exit", () => resolve()));
  const ready = Promise.withResolvers<string>();
  child.once("exit", (code) => ready.reject(new Error(`${name} stopped: ${code}`)));
  let errors = "";
  child.stderr.on("data", (data) => { errors += String(data); });
  createInterface({ input: child.stdout }).on("line", (line) => {
    const token = /^Token:\s*(\S+)/.exec(line)?.[1];
    if (token) ready.resolve(token);
  });
  try {
    const token = await ready.promise;
    return { home, host: `http://127.0.0.1:${port}`, token, stop: async () => { child.kill("SIGTERM"); await exit; } };
  } catch (error) { throw new Error(`${error}: ${errors}`); }
}

async function enable(home: string, origin: string) {
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(home, origin);
    yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
  }).pipe(Effect.scoped));
}

async function link(home: string, origin: string, target: { home: string; host: string }) {
  const output = await runPromise(makeState(target.home).cli(["auth", "pairing", "create", "--json"]));
  const { credential } = JSON.parse(output.stdout);
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(home, origin);
    yield* client["peerLinks.link"]({ url: target.host, pairingCode: credential, access: "full-access" });
  }).pipe(Effect.scoped));
}

test("Russian batch warning refers to all 21 unlisted machines and keeps the singular for one", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("demo");
  const origin = app.baseUrl ?? "";
  await enable(T3_HOME, origin);
  const second = await machine("B", origin);
  const targets: string[] = [];
  try {
    await enable(second.home, second.host);
    for (let start = 1; start <= 21; start += 3) {
      const batch = await Promise.all(Array.from({ length: 3 }, async (_, offset) => {
        const index = start + offset;
        const target = await machine(`Target ${String(index).padStart(2, "0")}`, origin);
        try {
          await enable(target.home, target.host);
          const id = await runPromise(environmentId(target.host));
          await link(second.home, second.host, target);
          return id;
        } finally { await target.stop(); }
      }));
      targets.push(...batch);
    }
    const secondId = await runPromise(environmentId(second.host));
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const add = screen.getByRole("dialog");
    await add.getByPlaceholder("backend.example.com").fill(second.host);
    await add.getByPlaceholder("PAIRCODE").fill(second.token);
    await add.getByRole("button", "Add environment").tap();
    await browser.locator(`[data-fleet-node="env:${secondId}"]`).waitFor({ timeout: 60_000 });
    await t3.open("/settings/general");
    await screen.getByLabel("Language", { exact: true }).tap();
    await screen.getByText("Русский", { exact: true }).tap();
    await t3.open("/settings/connections");
    const stack = browser.locator('[data-fleet-node^="stack:"]');
    await stack.waitFor();
    await screen.getByRole("button", "Показать каждую машину на карте", { exact: true }).tap();
    for (const id of [secondId, ...targets]) {
      const node = browser.locator(`[data-fleet-node="env:${id}"]`);
      await node.focus();
      await browser.keyboard.press("Space");
    }
    const handle = screen.getByRole("button", /Привязать Scenario к другой машине/);
    await handle.tap();
    const warning21 = screen.getByText(/21 машине нужен код сопряжения, поэтому/);
    await warning21.waitFor();
    await app.screenshot("21-unlisted-machines");
    const actual21 = await warning21.textContent();
    await browser.keyboard.press("Escape");
    for (const id of targets.slice(1)) {
      await browser.locator(`[data-fleet-node="env:${id}"]`).focus();
      await browser.keyboard.press("Space");
    }
    await handle.tap();
    const warning1 = screen.getByText(/1 машине нужен код сопряжения, поэтому/);
    await warning1.waitFor();
    await app.screenshot("one-unlisted-machine-control");
    await expect(warning1).toHaveText("1 машине нужен код сопряжения, поэтому её нет в списке.");
    expect(actual21).toBe("21 машине нужен код сопряжения, поэтому их нет в списке.");
  } finally { await second.stop(); }
});
