import fs from "node:fs";
import path from "node:path";
const DECORATOR_EXPORT_NAMES = [
  "Entity",
  "PrimaryKey",
  "Property",
  "ManyToOne",
  "OneToMany",
  "OneToOne",
  "ManyToMany",
  "Enum",
  "Index",
  "Unique",
  "Embeddable",
  "Embedded",
  "Formula"
];
const RECOVERY_VERSION = "mikro-orm-v7-generated-cache-recovery-v1";
const RECOVERY_MARKER_FILE = ".mikro-orm-v7-cache-recovery.json";
const GENERATED_DIR_SEGMENTS = [".mercato", "generated"];
const staleDecoratorImportPattern = new RegExp(
  String.raw`import\s*\{[^}]*\b(?:${DECORATOR_EXPORT_NAMES.join("|")})\b[^}]*\}\s*from\s*['"]@mikro-orm/core['"]`,
  "m"
);
const decoratorExportErrorPattern = /@mikro-orm\/core' does not provide an export named '(?:Entity|PrimaryKey|Property|ManyToOne|OneToMany|OneToOne|ManyToMany|Enum|Index|Unique|Embeddable|Embedded|Formula)'/;
function getGeneratedDir(appRoot) {
  return path.join(appRoot, ...GENERATED_DIR_SEGMENTS);
}
function getRecoveryMarkerPath(appRoot) {
  return path.join(getGeneratedDir(appRoot), RECOVERY_MARKER_FILE);
}
function walkFiles(dirPath) {
  if (!fs.existsSync(dirPath)) return [];
  const entries = fs.readdirSync(dirPath, { withFileTypes: true });
  const files = [];
  for (const entry of entries) {
    const absolutePath = path.join(dirPath, entry.name);
    if (entry.isDirectory()) {
      files.push(...walkFiles(absolutePath));
      continue;
    }
    if (entry.isFile()) {
      files.push(absolutePath);
    }
  }
  return files;
}
function listGeneratedCacheFiles(appRoot) {
  return walkFiles(getGeneratedDir(appRoot)).filter((filePath) => filePath.endsWith(".mjs")).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
}
function findStaleGeneratedCacheFiles(appRoot) {
  const generatedFiles = listGeneratedCacheFiles(appRoot);
  return generatedFiles.filter((filePath) => {
    const source = fs.readFileSync(filePath, "utf8");
    return staleDecoratorImportPattern.test(source);
  });
}
function writeRecoveryMarker(appRoot, marker) {
  const markerPath = getRecoveryMarkerPath(appRoot);
  fs.writeFileSync(markerPath, JSON.stringify(marker, null, 2));
  return markerPath;
}
function logRecoveryMessage(logger, reason) {
  const header = reason === "runtime-import-error" ? "\u26A0\uFE0F  Open Mercato detected a stale generated cache while bootstrapping the app." : "\u26A0\uFE0F  Open Mercato detected stale generated cache from the MikroORM v7 migration.";
  logger.warn("");
  logger.warn(header);
  logger.warn("\u{1F4D8} Open Mercato migrated MikroORM to version 7. Please review UPGRADE_NOTES.md and the `migrate-mikro-orm` skill if your code still imports decorators from `@mikro-orm/core`.");
  logger.warn("\u{1F9F9} Cleaning generated compilation cache and recompiling generated code now...");
  logger.warn("");
}
function deleteGeneratedCacheFiles(filePaths) {
  const deletedFiles = [];
  for (const filePath of filePaths) {
    if (!fs.existsSync(filePath)) continue;
    fs.rmSync(filePath, { force: true });
    deletedFiles.push(filePath);
  }
  return deletedFiles;
}
function applyGeneratedCacheRecovery(appRoot, staleFiles, reason, logger) {
  if (staleFiles.length === 0) {
    return { applied: false, deletedFiles: [], markerPath: null };
  }
  logRecoveryMessage(logger, reason);
  const generatedCacheFiles = listGeneratedCacheFiles(appRoot);
  const deletedFiles = deleteGeneratedCacheFiles(generatedCacheFiles);
  const markerPath = writeRecoveryMarker(appRoot, {
    version: RECOVERY_VERSION,
    reason,
    createdAt: (/* @__PURE__ */ new Date()).toISOString(),
    deletedFiles
  });
  return {
    applied: true,
    deletedFiles,
    markerPath
  };
}
function shouldRecoverMikroOrmV7GeneratedCache(error) {
  const message = error instanceof Error ? error.message : String(error);
  return decoratorExportErrorPattern.test(message);
}
function ensureMikroOrmV7GeneratedCacheCompatibility(appRoot, options = {}) {
  const logger = options.logger ?? console;
  const staleFiles = findStaleGeneratedCacheFiles(appRoot);
  return applyGeneratedCacheRecovery(appRoot, staleFiles, "stale-generated-cache-scan", logger);
}
function recoverMikroOrmV7GeneratedCacheFromImportError(appRoot, error, options = {}) {
  if (!shouldRecoverMikroOrmV7GeneratedCache(error)) {
    return { applied: false, deletedFiles: [], markerPath: null };
  }
  const logger = options.logger ?? console;
  const staleFiles = findStaleGeneratedCacheFiles(appRoot);
  return applyGeneratedCacheRecovery(appRoot, staleFiles, "runtime-import-error", logger);
}
export {
  ensureMikroOrmV7GeneratedCacheCompatibility,
  recoverMikroOrmV7GeneratedCacheFromImportError,
  shouldRecoverMikroOrmV7GeneratedCache
};
//# sourceMappingURL=generatedCacheRecovery.js.map
