// V1 -> V2 migration. Reads pbps_mis (SELECT only), writes pbps_v2 and pbps_legacy.
//   tsx migration/run-migration.ts --fresh --label rehearsal-1
import "dotenv/config";
import { createHash } from "node:crypto";
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import mysql, { type ResultSetHeader, type RowDataPacket } from "mysql2/promise";
import { splitSql } from "./split-sql.js";
import { archive } from "./archive.js";
import { typeCast } from "../src/core/db/db.js";
import { NAMES, named } from "./names.js";
import { reconcile, type Check } from "./reconcile.js";

const arg = (name: string) => { const i = process.argv.indexOf(`--${name}`); return i < 0 ? undefined : process.argv[i + 1]; };
const label = arg("label") ?? "manual";
const uri = process.env["MIGRATION_DATABASE_URL"];
if (!uri) throw new Error("MIGRATION_DATABASE_URL is not set");
const here = import.meta.dirname;
const db = await mysql.createConnection({ uri: uri.replace(/\/[^/]*$/, `/${NAMES["pbps_mis"]}`), charset: "utf8mb4_unicode_ci", timezone: "Z", dateStrings: true, typeCast: typeCast as never });
const raw = db.query.bind(db) as (...a: unknown[]) => Promise<never>;
db.query = ((sql: unknown, ...rest: unknown[]) => raw(typeof sql === "string" ? named(sql) : sql, ...rest)) as typeof db.query;
await db.query("SET SESSION sql_mode='STRICT_ALL_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO', time_zone='+00:00'");

// The source must be read-only for this user, otherwise stop.
const [grants] = await db.query<RowDataPacket[]>("SHOW GRANTS");
const own = grants.map((g) => String(Object.values(g)[0]));
const unsafe = own.filter((g) => (g.replace(/\\/g, "").includes(`ON \`${NAMES["pbps_mis"]}\``) && !/^GRANT SELECT ON/.test(g)) || (/ON \*\.\*/.test(g) && !/^GRANT USAGE/.test(g)));
if (unsafe.length) throw new Error("This user can write to pbps_mis. Refusing to run.");

const verifyOnly = process.argv.includes("--verify-only");
// --fresh destroys V2 data: only on this machine, and never once someone has registered a trainee that V1 does not have.
if (process.argv.includes("--fresh") && !verifyOnly) {
  if (!["127.0.0.1", "localhost"].includes(new URL(uri).hostname) || process.env["NODE_ENV"] === "production") throw new Error("--fresh is refused outside a local rehearsal.");
  const [exists] = await db.query<RowDataPacket[]>("SELECT 1 FROM information_schema.tables WHERE table_schema='pbps_v2' AND table_name='trainees'");
  if (exists.length && !process.argv.includes("--discard-test-data")) {
    const [added] = await db.query<RowDataPacket[]>("SELECT COUNT(*) AS n FROM pbps_v2.trainees v LEFT JOIN pbps_mis.trainees s ON s.id=v.id WHERE s.id IS NULL");
    if (Number(added[0]!["n"]) > 0) throw new Error("--fresh is refused: V2 holds trainees that V1 does not have. If they are only test records, add --discard-test-data.");
  }
}
if (process.argv.includes("--fresh") && !verifyOnly) for (const name of ["pbps_v2", "pbps_legacy"]) await db.query(`DROP DATABASE IF EXISTS ${name}`);

const scripts = readdirSync(join(here, "sql")).filter((f) => f.endsWith(".sql"));
const steps = readdirSync(join(here, "steps")).filter((f) => f.endsWith(".step.ts"));
const ordered = verifyOnly ? [] : [...scripts, ...steps].sort();
const t0 = Date.now();
for (const file of ordered) {
  const path = join(here, file.endsWith(".sql") ? "sql" : "steps", file);
  const text = readFileSync(path, "utf8");
  const started = Date.now();
  let affected = 0;
  const ddl = file.startsWith("01");
  if (file !== "01_schema.sql") await db.query(file === "00_preflight.sql" ? "USE pbps_mis" : "USE pbps_v2");
  if (file === "00_preflight.sql") {
    for (const statement of splitSql(text)) {
      const [rows] = await db.query<RowDataPacket[]>(statement);
      const [name, value] = Object.entries(rows[0] ?? {})[0] ?? [];
      if (Number(value) !== 0) throw new Error(`Preflight failed: ${name} = ${value}. V1 data must be looked at before migrating.`);
    }
  } else {
    if (!ddl) await db.beginTransaction();
    try {
      if (file.endsWith(".sql")) for (const statement of splitSql(text)) {
        try {
          const [r] = await db.query(statement);
          affected += (r as ResultSetHeader).affectedRows ?? 0;
        } catch (error) { throw new Error(`${file}: ${(error as Error).message}\n--- statement ---\n${statement.slice(0, 900)}`); }
      } else affected = await ((await import(pathToFileURL(path).href)) as { default: (c: mysql.Connection) => Promise<number> }).default(db);
      if (!ddl) await db.commit();
    } catch (error) { if (!ddl) await db.rollback(); throw error; }
    await db.query("INSERT INTO pbps_v2.migration_runs (run_label, script, started_at, finished_at, status, rows_affected, checksum) VALUES (?,?,?,UTC_TIMESTAMP(3),'ok',?,?)",
      [label, file, new Date(started).toISOString().slice(0, 23).replace("T", " "), affected, createHash("sha256").update(text).digest("hex")]);
  }
  console.log(`${file.padEnd(36)} ${String(affected).padStart(8)} rows  ${Date.now() - started} ms`);
}
// Fresh statistics: without them the first queries after a bulk load choose very slow plans.
const [loaded] = await db.query<RowDataPacket[]>("SELECT table_name AS t FROM information_schema.tables WHERE table_schema='pbps_v2'");
if (!verifyOnly) await db.query(`ANALYZE TABLE ${loaded.map((x) => `pbps_v2.\`${x["t"]}\``).join(",")}`);
const checks: Check[] = [...(verifyOnly ? [] : await archive(db)), ...(await reconcile(db))];
const failed = checks.filter((c) => !c.ok);
mkdirSync(join(here, "reports"), { recursive: true });
writeFileSync(join(here, "reports", `reconciliation-${label}.md`), `# Reconciliation: ${label}\n\n${checks.length - failed.length} of ${checks.length} checks passed.\n\n| | Check | V1 | V2 |\n|---|---|---|---|\n${checks.map((c) => `| ${c.ok ? "ok" : "**FAIL**"} | ${c.name} | ${c.v1} | ${c.v2} |`).join("\n")}\n`);
for (const c of failed) console.log("FAIL", c.name, "V1:", c.v1, "V2:", c.v2);
console.log(`${checks.length - failed.length} of ${checks.length} checks passed in ${Math.round((Date.now() - t0) / 1000)} s`);
await db.end();
await (await import("../src/core/db/db.js")).pool.end();
if (failed.length) process.exitCode = 1;
