import { spawn } from "node:child_process";
import { createHash } from "node:crypto";
import { createReadStream, createWriteStream } from "node:fs";
import { copyFile, mkdir, readdir, rename, stat } from "node:fs/promises";
import { join } from "node:path";
import { pipeline } from "node:stream/promises";
import { createGunzip, createGzip } from "node:zlib";
import mysql from "mysql2/promise";
import { env } from "../../config/env.js";
import { poolOptions } from "../../core/db/db.js";

const url = () => new URL(env.BACKUP_DATABASE_URL!);
export const CHECK_DB = () => `${new URL(env.DATABASE_URL).pathname.slice(1)}_restore_check`;
const program = (name: string) => (env.MYSQL_BIN_DIR ? join(env.MYSQL_BIN_DIR, process.platform === "win32" ? `${name}.exe` : name) : name);
/** The password goes through the environment, so it never shows in the list of running programs. */
function start(name: string, args: string[]) {
  const u = url(), p = spawn(program(name), [`--host=${u.hostname}`, `--port=${u.port || "3306"}`, `--user=${decodeURIComponent(u.username)}`, "--default-character-set=utf8mb4", ...args], { env: { ...process.env, MYSQL_PWD: decodeURIComponent(u.password) }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
  let errors = "";
  p.stderr.on("data", (b: Buffer) => { errors = (errors + b.toString()).slice(-2000); });
  const done = new Promise<void>((ok, no) => { p.on("error", (e) => no(new Error(`${name} could not start: ${e.message}`))); p.on("close", (code) => (code === 0 ? ok() : no(new Error(`${name} failed: ${errors.trim() || `code ${code}`}`)))); });
  done.catch(() => undefined);
  return { p, done };
}
async function all<T>(work: Promise<T>, done: Promise<void>): Promise<void> {
  const [a, b] = await Promise.allSettled([work, done]);
  if (b.status === "rejected") throw b.reason;
  if (a.status === "rejected") throw a.reason;
}
export async function dump(db: string, file: string): Promise<void> {
  const { p, done } = start("mysqldump", ["--single-transaction", "--quick", "--hex-blob", "--skip-triggers", "--net-buffer-length=400K", db]);
  p.stdin.end();
  await all(pipeline(p.stdout, createGzip({ level: 6 }), createWriteStream(file, { flags: "wx" })), done);
}
export async function load(file: string, db: string): Promise<void> {
  const { p, done } = start("mysql", [db]);
  p.stdout.resume();
  await all(pipeline(createReadStream(file), createGunzip(), p.stdin), done);
}
const connect = (db?: string) => mysql.createConnection({ ...poolOptions(env.BACKUP_DATABASE_URL!), ...(db ? { database: db } : {}) } as mysql.ConnectionOptions);
export async function counts(db: string): Promise<Record<string, number>> {
  const c = await connect(db);
  try {
    const [tables] = await c.query<mysql.RowDataPacket[]>("SELECT table_name AS t FROM information_schema.tables WHERE table_schema=? AND table_type='BASE TABLE'", [db]), out: Record<string, number> = {};
    for (const x of tables) { const [n] = await c.query<mysql.RowDataPacket[]>(`SELECT COUNT(*) AS n FROM \`${x["t"]}\``); out[x["t"] as string] = Number(n[0]!["n"]); }
    return out;
  } finally { await c.end(); }
}
export async function restoreCheck(db: string, file: string): Promise<Record<string, number>> {
  const name = CHECK_DB();
  if (name === db) throw new Error("The test database cannot be the real one.");
  const c = await connect("information_schema");
  try {
    await c.query(`DROP DATABASE IF EXISTS \`${name}\``);
    await c.query(`CREATE DATABASE \`${name}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`);
    await load(file, name);
    return await counts(name);
  } finally { await c.query(`DROP DATABASE IF EXISTS \`${name}\``); await c.end(); }
}
export async function sha256File(file: string): Promise<string> {
  const h = createHash("sha256");
  await pipeline(createReadStream(file), h);
  return h.digest("hex");
}
/** Uploaded files never change, so only new ones are copied and nothing is ever removed from the backup. */
export async function copyTree(from: string, to: string): Promise<number> {
  let n = 0;
  for (const e of await readdir(from, { withFileTypes: true }).catch(() => [])) {
    if (e.name === ".incoming") continue; // uploads that are still arriving
    const a = join(from, e.name), b = join(to, e.name);
    if (e.isDirectory()) { n += await copyTree(a, b); continue; }
    if (!e.isFile()) continue;
    n++;
    if ((await stat(b).catch(() => null))?.size === (await stat(a)).size) continue;
    await mkdir(to, { recursive: true });
    await copyFile(a, `${b}.part`);
    if ((await sha256File(a)) !== (await sha256File(`${b}.part`))) throw new Error(`The copy of ${e.name} is damaged.`);
    await rename(`${b}.part`, b);
  }
  return n;
}
