import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { readFileSync, readlinkSync, utimesSync } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB, makeState, runPromise } from "./t3.ts";

test("A started queued message remains visible after server restart", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Restart demo");
  await t3.open();
  const cli = async (args: string[]) => (await runPromise(makeState(T3_HOME).cli(args))).stdout;
  const query = (sql: string) => JSON.parse(execFileSync("sqlite3", ["-readonly", "-json", `${T3_HOME}/userdata/statev2.sqlite`, sql], { encoding: "utf8" }) || "[]");
  const runtime = JSON.parse(readFileSync(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const port = new URL(runtime.origin).port;
  const listeners = execFileSync("ss", ["-H", "-ltnp", `sport = :${port}`], { encoding: "utf8" });
  const pid = Number(/pid=(\d+)/.exec(listeners)?.[1]);
  if (!pid || !readlinkSync(`/proc/${pid}/cwd`).startsWith(APP_DIR + "/")) throw new Error("Server owner cwd did not match app checkout");
  const started = JSON.parse(await cli(["thread", "start", "--provider", "devReplay", "--model", "showcase", project, "first turn", "--title", "Restart visibility", "--json"]));
  const threadId = started.threadId;
  let stopped = false;
  const watch = (async () => {
    for (let i = 0; i < 2000; i++) {
      const rows = query(`SELECT status,payload_json FROM orchestration_v2_projection_runs WHERE thread_id='${threadId}' ORDER BY ordinal`);
      if (rows[1]?.status === "running" && JSON.parse(rows[1].payload_json).startedAt && query(`SELECT 1 FROM orchestration_v2_projection_provider_turns WHERE run_attempt_id='${JSON.parse(rows[1].payload_json).activeAttemptId}' AND status='running'`).length > 0) {
        process.kill(pid, "SIGTERM");
        stopped = true;
        for (let j = 0; j < 500; j++) {
          try { process.kill(pid, 0); } catch { break; }
          await delay(20);
        }
        const now = new Date();
        utimesSync(`${APP_DIR}/apps/server/src/bin.ts`, now, now);
        return;
      }
      await delay(10);
    }
    throw new Error("Queued run did not start");
  })();
  await cli(["thread", "send", threadId, "SECOND QUEUED MESSAGE marker-41290", "--json"]);
  await t3.open({ threadId });
  await watch;
  if (!stopped) throw new Error("Restart did not occur");
  for (let i = 0; i < 1500; i++) {
    const rows = query(`SELECT status,payload_json FROM orchestration_v2_projection_runs WHERE thread_id='${threadId}' ORDER BY ordinal`);
    if (rows.length >= 3 && rows[2].status === "completed") break;
    if (i === 1499) throw new Error("Restart continuation did not complete");
    await delay(100);
  }
  await t3.open({ threadId });
  await screen.getByText("T3 Code restarted and resumed this turn", { exact: false }).first().waitFor({ state: "visible" });
  await screen.getByText("T3 Code restarted and resumed this turn", { exact: false }).first().scrollIntoView();
  await browser.evaluate(() => {
    const notice = [...document.querySelectorAll("*")].reverse().find((element) => element.textContent?.trim() === "T3 Code restarted and resumed this turn");
    notice?.scrollIntoView({ block: "center", behavior: "instant" });
  });
  await app.screenshot("queued-message-after-restart");
  await expect(screen.getByText("SECOND QUEUED MESSAGE marker-41290", { exact: true }).first()).toBeVisible();
});
