import fs from 'fs';
import path from 'path';
import { pathToFileURL } from 'url';
import { createRequire } from 'module';

const ROOT = process.cwd();
const CANDIDATES = ['', 'lib', 'src', '.'];
const req = createRequire(import.meta.url);

export function resolveModule(name) {
  for (const base of CANDIDATES) {
    const p = path.join(ROOT, base, `${name}.js`);
    if (fs.existsSync(p)) return p;
  }
  return null;
}

export async function safeImport(name) {
  const p = resolveModule(name);
  if (!p) return { ok:false, reason:`Module not found: ${name}` };
  try {
    const mod = await import(pathToFileURL(p).href);
    return normalize(mod, p);
  } catch (e1) {
    try {
      const mod = req(p);
      return normalize(mod, p);
    } catch (e2) {
      return { ok:false, reason:`Failed to load ${name}: ${e1.message} | ${e2.message}` };
    }
  }
}
function normalize(mod, p) {
  const m = mod?.default && typeof mod.default === 'object'
    ? { ...mod.default, ...mod }
    : mod;
  return { ok:true, mod:m, path:p };
}
