import dotenv from "dotenv";
import { loadConfig } from "../config.js";
import { closeDb, initDb } from "../db.js";
import { ensureSchema, seedLevelsCatalog } from "../server/db-schema.js";

type CliOptions = {
  yes: boolean;
  backup: boolean;
  reset: boolean;
  backupTableName?: string;
};

const parseArgs = (argv: string[]): CliOptions => {
  const options: CliOptions = {
    yes: false,
    backup: true,
    reset: true,
  };

  for (let index = 0; index < argv.length; index += 1) {
    const token = argv[index];
    if (token === "--yes") {
      options.yes = true;
      continue;
    }
    if (token === "--no-backup") {
      options.backup = false;
      continue;
    }
    if (token === "--keep-run-data") {
      options.reset = false;
      continue;
    }
    if (token === "--backup-table") {
      const value = argv[index + 1];
      if (!value || value.startsWith("--")) {
        throw new Error("Option --backup-table attend une valeur.");
      }
      options.backupTableName = value.trim();
      index += 1;
      continue;
    }
    throw new Error(`Option inconnue: ${token}`);
  }

  return options;
};

const printUsage = () => {
  console.log(
    [
      "Usage:",
      "  node dist/scripts/reseed-levels-catalog.js --yes [--no-backup] [--keep-run-data] [--backup-table <name>]",
      "",
      "Options:",
      "  --yes              Confirme l'opération destructive.",
      "  --no-backup        Ne crée pas de backup de levels_catalog.",
      "  --keep-run-data    Ne vide pas leaderboard_entries/recent_runs/level_stats.",
      "  --backup-table     Nom explicite de table backup.",
    ].join("\n"),
  );
};

const run = async () => {
  dotenv.config({ path: ".env" });

  const options = parseArgs(process.argv.slice(2));
  if (!options.yes) {
    printUsage();
    throw new Error("Confirmation manquante: ajoute --yes.");
  }

  const config = loadConfig();
  const db = initDb(config);

  try {
    await ensureSchema(db);
    const result = await seedLevelsCatalog(db, {
      force: true,
      backupBeforeReplace: options.backup,
      resetRunAndLeaderboardData: options.reset,
      backupTableName: options.backupTableName,
      log: (message) => console.log(`[reseed] ${message}`),
    });

    console.log(
      JSON.stringify(
        {
          ok: true,
          ...result,
        },
        null,
        2,
      ),
    );
  } finally {
    await closeDb();
  }
};

run().catch((error) => {
  const message = error instanceof Error ? error.message : String(error);
  console.error(`[reseed] ERREUR: ${message}`);
  process.exit(1);
});
