// Turns a V1 production database into a new V2 database:
//   npm run convert:production -- <dump.sql> --uploads <folder>          a file exported from the server
//   npm run convert:production -- --database <name> --uploads <folder>   a copy already imported in phpMyAdmin
// It only ever creates NEW databases. The dump, V1 and the V2 in use are never changed.
import "dotenv/config";
import { execFileSync, spawn } from "node:child_process";
import { createReadStream, existsSync, readFileSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { createInterface } from "node:readline";
import mysql, { type RowDataPacket } from "mysql2/promise";

const args = process.argv.slice(2), flag = (n: string) => { const i = args.indexOf(`--${n}`); return i < 0 ? undefined : args[i + 1]; };
const dump = args[0] && !args[0].startsWith("--") ? resolve(args[0]) : undefined, stamp = new Date().toISOString().slice(0, 16).replace(/\D/g, "").slice(0, 12);
const source = flag("database") ?? `v1_prod_${stamp}`, target = `v2_prod_${stamp}`, archive = `${target}_v1_archive`, uploads = flag("uploads");
const fail = (m: string): never => { console.error(`\nSTOPPED: ${m}\nNothing in V1 or in the V2 in use was changed.`); process.exit(1); };
if (!dump && !flag("database")) fail("Give the dump file, or --database <name>.");
if (dump && !existsSync(dump)) fail(`${dump} does not exist.`);
if (!uploads) fail("Give V1's uploads folder with --uploads <folder>, so no evidence file is lost.");
if (uploads && !existsSync(uploads)) fail(`${uploads} does not exist.`);
if (!/^\w{1,50}$/.test(source)) fail("The database name may hold only letters, numbers and _.");
const migrator = new URL(process.env["MIGRATION_DATABASE_URL"] ?? fail("MIGRATION_DATABASE_URL is not set.")), admin = new URL(process.env["CONVERT_ADMIN_URL"] ?? `mysql://root@${migrator.hostname}:${migrator.port || 3306}`);
const root = await mysql.createConnection({ host: admin.hostname, port: Number(admin.port || 3306), user: decodeURIComponent(admin.username), password: decodeURIComponent(admin.password) }).catch((e: Error) => fail(`Cannot reach MySQL as ${admin.username}: ${e.message}. Start it, or set CONVERT_ADMIN_URL.`));
const names = async () => new Set(((await root.query<RowDataPacket[]>("SELECT schema_name AS n FROM information_schema.schemata"))[0]).map((x) => String(x["n"])));
const have = await names();
for (const n of [target, archive, ...(dump ? [source] : [])]) if (have.has(n)) fail(`The database ${n} already exists. Wait a minute and try again.`);

if (dump) {
  console.log(`1/6  Importing ${dump} into the new database ${source} ...`);
  await root.query(`CREATE DATABASE \`${source}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`);
  const bin = process.env["MYSQL_BIN_DIR"], p = spawn(bin ? join(bin, process.platform === "win32" ? "mysql.exe" : "mysql") : "mysql", [`--host=${admin.hostname}`, `--port=${admin.port || 3306}`, `--user=${decodeURIComponent(admin.username)}`, "--default-character-set=utf8mb4", "--max-allowed-packet=64M", source], { env: { ...process.env, MYSQL_PWD: decodeURIComponent(admin.password) }, stdio: ["pipe", "ignore", "pipe"] });
  let err = "";
  p.stderr.on("data", (b: Buffer) => { err += b.toString(); });
  const done = new Promise<number>((ok) => p.on("close", (c) => ok(c ?? 1)));
  p.stdin.on("error", () => undefined);
  let lines = 0, dropped = 0;
  // A dump may say which database to write to. Those lines are left out, so it can only go into the new one.
  for await (const line of createInterface({ input: createReadStream(dump, "utf8"), crlfDelay: Infinity })) {
    if (/^\s*(\/\*!\d+\s*)?(CREATE|DROP|ALTER)\s+DATABASE|^\s*USE\s+`?[\w-]+`?\s*;\s*$/i.test(line)) { dropped++; continue; }
    lines++;
    if (!p.stdin.write(`${line}\n`)) await new Promise((r) => p.stdin.once("drain", r));
    if (p.exitCode !== null) break;
  }
  p.stdin.end();
  if (await done) fail(`The import failed: ${err.trim().slice(0, 500)}`);
  console.log(`     ${lines} lines read${dropped ? `, ${dropped} lines naming a database left out` : ""}.`);
} else if (!have.has(source)) fail(`The database ${source} does not exist.`);

console.log("2/6  Comparing its tables with the V1 this conversion was written for ...");
const shape = async () => { const [r] = await root.query<RowDataPacket[]>("SELECT table_name AS t, column_name AS c, data_type AS d FROM information_schema.columns WHERE table_schema=? ORDER BY 1,2", [source]); const out: Record<string, Record<string, string>> = {}; for (const x of r) (out[x["t"]] ??= {})[x["c"]] = x["d"]; return out; };
const file = join(import.meta.dirname, "..", "migration", "data", "v1-schema.json"), now = await shape();
if (args.includes("--save-schema")) { writeFileSync(file, JSON.stringify(now, null, 1)); console.log("     Saved."); process.exit(0); }
const known = JSON.parse(readFileSync(file, "utf8")) as typeof now, missing: string[] = [], extra: string[] = [];
for (const [t, cols] of Object.entries(known)) { if (!now[t]) { missing.push(`table ${t}`); continue; } for (const c of Object.keys(cols)) if (!now[t]![c]) missing.push(`column ${t}.${c}`); }
for (const [t, cols] of Object.entries(now)) { if (!known[t]) { extra.push(`table ${t}`); continue; } for (const c of Object.keys(cols)) if (!known[t]![c]) extra.push(`column ${t}.${c}`); }
if (missing.length) fail(`This V1 has no ${missing.join(", ")}. The conversion needs them.`);
if (extra.length && !args.includes("--accept-new-columns")) fail(`This V1 is newer and also has: ${extra.join(", ")}.\nThe conversion does not carry them into V2 yet. Have the conversion extended first, so nothing is lost.\n(Their data is always kept in the archive. To go on anyway: --accept-new-columns)`);
console.log(extra.length ? `     Accepted as archive-only: ${extra.join(", ")}` : "     The same.");

console.log(`3/6  Preparing ${target} ...`);
const esc = (n: string) => `\`${n.replace(/_/g, "\\_")}\``, app = new URL(process.env["DATABASE_URL"]!), backup = process.env["BACKUP_DATABASE_URL"] ? new URL(process.env["BACKUP_DATABASE_URL"]) : null;
for (const h of ["localhost", "127.0.0.1"]) {
  const u = async (url: URL, grants: [string, string][]) => { const [x] = await root.query<RowDataPacket[]>("SELECT 1 FROM mysql.user WHERE user=? AND host=?", [url.username, h]); if (x.length) for (const [what, db] of grants) await root.query(`GRANT ${what} ON ${esc(db)}.* TO '${url.username}'@'${h}'`); };
  await u(migrator, [["SELECT", source], ["ALL", target], ["ALL", archive]]);
  await u(app, [["SELECT,INSERT,UPDATE,DELETE", target], ["SELECT", archive]]);
  if (backup) await u(backup, [["SELECT,LOCK TABLES,SHOW VIEW", target], ["SELECT,LOCK TABLES,SHOW VIEW", archive], ["ALL", `${target}_restore_check`]]);
}
await root.end();

console.log("4/6  Converting. V1 is opened read-only ...");
const to = (u: URL) => { const x = new URL(u.href); x.pathname = `/${target}`; return x.href; };
const env = { ...process.env, SOURCE_DB: source, ARCHIVE_DB: archive, MIGRATION_DATABASE_URL: to(migrator), DATABASE_URL: to(app), V1_UPLOADS_DIR: resolve(uploads!) };
let failed = false;
try { execFileSync(process.execPath, ["--import", "tsx", join(import.meta.dirname, "..", "migration", "run-migration.ts"), "--label", `production-${stamp}`], { env, stdio: "inherit", cwd: join(import.meta.dirname, "..") }); } catch { failed = true; }
// Only after the copy was compared with V1: the corrections the owner of the data decided (see the file).
console.log("5/6  Correcting the reports of the people below 80 % who were reported as staying ...");
try { execFileSync(process.execPath, ["--import", "tsx", join(import.meta.dirname, "correct-low-attendance.ts")], { env, stdio: "inherit", cwd: join(import.meta.dirname, "..") }); } catch { failed = true; }
console.log(`6/6  ${failed ? "Some checks FAILED: read the lines marked FAIL above before using it." : "Every check passed."}
     Full report: migration/reports/reconciliation-production-${stamp}.md

To use it, put these lines in backend/.env (the migration line in backend/.env.migration) and start V2 again:
  DATABASE_URL=${to(app).replace(/:[^:@/]+@/, ":<same password>@")}
  MIGRATION_DATABASE_URL=${to(migrator).replace(/:[^:@/]+@/, ":<same password>@")}${backup ? `\n  BACKUP_DATABASE_URL=${to(backup).replace(/:[^:@/]+@/, ":<same password>@")}` : ""}
Until then V2 keeps using its present database.`);
process.exit(failed ? 1 : 0);
