import { createRequire } from "node:module";

const require = createRequire(import.meta.url);
const DEFAULT_ELK_MODULE = "elkjs/lib/elk.bundled.js";
const runtimeCache = new Map();

function normalizeElkExport(mod) {
  if (!mod) {
    return null;
  }
  if (typeof mod === "function") {
    return mod;
  }
  if (typeof mod.default === "function") {
    return mod.default;
  }
  if (typeof mod.ELK === "function") {
    return mod.ELK;
  }
  if (mod.default && typeof mod.default.ELK === "function") {
    return mod.default.ELK;
  }
  return null;
}

export function resolveElkRuntime(moduleId = DEFAULT_ELK_MODULE) {
  const key = String(moduleId || DEFAULT_ELK_MODULE);
  if (runtimeCache.has(key)) {
    return runtimeCache.get(key);
  }

  let state;
  try {
    const loaded = require(key);
    const ElkCtor = normalizeElkExport(loaded);
    if (!ElkCtor) {
      state = {
        ok: false,
        module: key,
        reason: "invalid_export",
        message: `ELK module "${key}" loaded but did not expose a usable constructor.`
      };
    } else {
      state = {
        ok: true,
        module: key,
        ElkCtor
      };
    }
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    state = {
      ok: false,
      module: key,
      reason: "module_load_failed",
      message: `ELK module "${key}" unavailable: ${message}`
    };
  }

  runtimeCache.set(key, state);
  return state;
}
