// usage: node drive.ts <idle100|idle30s> <seconds> <dir>
import * as NodeSqlite from "node:sqlite";
import * as fs from "node:fs";
import * as path from "node:path";
import { execSync } from "node:child_process";
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/sql/SqlClient";

const [variant = "idle100", secondsArg = "40", dir = "/tmp/ck"] = process.argv.slice(2);
const seconds = Number(secondsArg);
const mod = await import(`./client-${variant}.ts`);
fs.mkdirSync(dir, { recursive: true });
const base = path.join(dir, "base.sqlite");
if (!fs.existsSync(base)) {
  const b = new NodeSqlite.DatabaseSync(base);
  b.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, k TEXT, v TEXT); CREATE INDEX ik ON t(k); BEGIN");
  const ins = b.prepare("INSERT INTO t(k, v) VALUES (?, ?)");
  for (let i = 0; i < 20000; i++) ins.run(Math.random().toString(16).slice(2), "x".repeat(3000));
  b.exec("COMMIT");
  b.close();
}
const file = path.join(dir, `run-${variant}-${Date.now()}.sqlite`);
fs.copyFileSync(base, file);
execSync("sync");
await new Promise((r) => setTimeout(r, 2000));

const writeBytes = () =>
  Number(/write_bytes: (\d+)/.exec(fs.readFileSync("/proc/self/io", "utf8"))![1]);
const hex = (n: number) => Array.from({ length: n }, () => Math.floor(Math.random() * 16).toString(16)).join("");
const expo = (mean: number) => -Math.log(1 - Math.random()) * mean;

const program = Effect.gen(function* () {
  const sql = yield* SqlClient.SqlClient;
  // Same pragmas as apps/server/src/persistence/Sqlite.ts.
  yield* sql`PRAGMA busy_timeout = 5000`;
  yield* sql`PRAGMA journal_mode = WAL`;
  yield* sql`PRAGMA synchronous = NORMAL`;
  yield* sql`PRAGMA checkpoint_fullfsync = ON`;
  yield* sql.unsafe(`PRAGMA journal_size_limit = ${32 * 1024 * 1024}`);
  const probe = new NodeSqlite.DatabaseSync(file);
  const noop = probe.prepare("PRAGMA wal_checkpoint(NOOP)");
  const w0 = writeBytes();
  const t0 = Date.now();
  let commits = 0, frames = 0, resets = 0, pending = 0;
  while (Date.now() - t0 < seconds * 1000) {
    yield* sql.withTransaction(
      Effect.gen(function* () {
        for (let i = 0; i < 8; i++) {
          const id = 1 + Math.floor(Math.random() * 20000);
          yield* sql`UPDATE t SET v = ${hex(8).repeat(375)}, k = ${hex(16)} WHERE id = ${id}`;
        }
      }),
    );
    commits++;
    const log = Number((noop.get() as { log: number }).log);
    if (log >= pending) frames += log - pending;
    else { frames += log; resets++; }
    pending = log;
    yield* Effect.sleep(Math.round(expo(160)));
  }
  probe.close();
  execSync("sync");
  const dt = (Date.now() - t0) / 1000;
  const written = writeBytes() - w0;
  const walBytes = frames * 4120;
  console.log(
    JSON.stringify({
      variant, seconds: dt, commits, walFrames: frames, walResets: resets,
      writtenMiB: +(written / 2 ** 20).toFixed(1),
      writtenMiBPerMin: +((written / 2 ** 20) * 60 / dt).toFixed(1),
      walMiBPerMin: +((walBytes / 2 ** 20) * 60 / dt).toFixed(1),
      writesPerWalByte: +(written / walBytes).toFixed(2),
    }),
  );
});

await Effect.runPromise(
  program.pipe(Effect.provide(mod.layer({ filename: file, writerWorker: true })), Effect.scoped),
);
fs.rmSync(file); fs.rmSync(`${file}-wal`, { force: true }); fs.rmSync(`${file}-shm`, { force: true });
