import { execFileSync, spawn } from "node:child_process";
import { appendFileSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { expect } from "e2e";

import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const TURNS = Number(process.env.IO_TURNS ?? 5);
const OUT = process.env.IO_OUT ?? "/tmp/io-out";
const userdata = join(T3_HOME, "userdata");
const io = (label: string) => {
  const pid = JSON.parse(readFileSync(join(userdata, "server-runtime.json"), "utf8")).pid;
  appendFileSync(join(OUT, "marks.txt"), `${label} ${Date.now()} ${readFileSync(`/proc/${pid}/io`, "utf8").replace(/\n/g, " ")}\n`);
};

test("io measure: several replay turns in one thread", WEB, async ({ t3, screen }) => {
  await t3.project("demo", { "src/math.ts": "export const sum = 1 + 1;\n" });
  await t3.open();
  await new Promise((r) => setTimeout(r, 5000));
  const pid = JSON.parse(readFileSync(join(userdata, "server-runtime.json"), "utf8")).pid;
  const st = process.env.IO_STRACE ? spawn("sudo", ["-n", "strace", "-f", "-y", "-qq", "-e", "trace=write,pwrite64,writev,pwritev,pwritev2,fsync,fdatasync", "-o", join(OUT, "strace.txt"), "-p", String(pid)], { stdio: "ignore" }) : undefined;
  await new Promise((r) => setTimeout(r, 1000));
  io("before");
  for (let i = 0; i < TURNS; i++) {
    await screen.getByRole("textbox").fill(`Give me a short tour ${i}`);
    await screen.getByRole("textbox").press("Enter");
    await expect(screen.getByRole("button", "Stop generation")).toBeVisible();
    await expect(screen.getByRole("button", "Stop generation")).toBeHidden({ timeout: 60000 });
    io(`turn${i}`);
  }
  await new Promise((r) => setTimeout(r, 3000));
  io("after");
  st?.kill("SIGINT");
  await new Promise((r) => setTimeout(r, 1000));
  execFileSync("sqlite3", [join(userdata, "statev2.sqlite"), `.backup ${join(OUT, "db.sqlite")}`]);
});
