/// <reference lib="dom" />
import { readFileSync, readlinkSync } from "node:fs";
import { execFileSync, spawn } from "node:child_process";
import { once } from "node:events";
import { setTimeout as delay } from "node:timers/promises";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Scheduled-task base branch stays closed after reconnect", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  await runPromise(run("git", ["branch", "fix/example"], { cwd: project }));
  await t3.open("/settings/scheduled-tasks");
  const newTask = screen.getByRole("button", "New task");
  await newTask.waitFor({ timeout: 60000 });
  await newTask.click();
  const trigger = screen.getByRole("combobox", "Base branch");
  await trigger.tap();
  const search = browser.locator('input[placeholder="Search refs..."]');
  await search.fill("fix");
  await screen.getByRole("option", "fix/example").waitFor();
  await app.screenshot("filtered-before-disconnect");

  const { origin } = JSON.parse(readFileSync(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const port = new URL(origin).port;
  const listeners = execFileSync("ss", ["-H", "-ltnp", `sport = :${port}`], { encoding: "utf8" });
  const pid = Number(/pid=(\d+)/.exec(listeners)?.[1]);
  if (!pid) throw new Error("No scenario server port owner");
  const cwd = readlinkSync(`/proc/${pid}/cwd`);
  if (!cwd.startsWith(APP_DIR)) throw new Error("Port owner is outside scenario checkout");
  const argv = readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").filter(Boolean);
  const env = Object.fromEntries(readFileSync(`/proc/${pid}/environ`, "utf8").split("\0").filter(Boolean).map(value => {
    const split = value.indexOf("=");
    return [value.slice(0, split), value.slice(split + 1)];
  }));
  process.kill(pid, "SIGTERM");
  const disconnected = screen.getByText("Reconnect this environment before saving.", { exact: true });
  await disconnected.waitFor({ timeout: 60000 });
  await search.waitFor({ state: "hidden" });
  await app.screenshot("disconnected-picker-hidden");
  const restarted = spawn(argv[0]!, argv.slice(1), { cwd, env, stdio: "ignore" });
  try {
    await disconnected.waitFor({ state: "hidden", timeout: 60000 });
    await trigger.waitFor();
    // Wait until reconnection enables the form, without interacting with the picker.
    await browser.locator('#scheduled-task-base-ref:not([disabled])').waitFor();
    await app.screenshot("reconnected-picker");
    await expect(trigger).toHaveAttribute("aria-expanded", "false");
    await expect(search).toBeHidden();
    await trigger.tap();
    await expect(search).toHaveValue("");
    await app.screenshot("explicit-reopen-empty-search");
  } finally {
    const exited = once(restarted, "exit");
    restarted.kill("SIGTERM");
    await exited;
    // The fixture cleanup uses the server API; let the original watch launcher restart it.
    const { utimesSync } = await import("node:fs");
    utimesSync(`${APP_DIR}/apps/server/src/bin.ts`, new Date(), new Date());
    const deadline = Date.now() + 60000;
    while (true) {
      try { if ((await fetch(`${origin}/.well-known/t3/environment`)).ok) break; } catch {}
      if (Date.now() > deadline) throw new Error("Original scenario server did not restart");
      await delay(100);
    }
  }
});
