import fs from 'node:fs';
import path from 'node:path';

export async function loadPlugins(dir) {
  const plugins = [];
  if (!fs.existsSync(dir)) return plugins;
  for (const file of fs.readdirSync(dir).sort()) {
    if (!file.endsWith('.js') && !file.endsWith('.mjs')) continue;
    const mod = await import(path.join(dir, file));
    const plugin = mod.default ?? mod;
    if (plugin && typeof plugin === 'object') {
      plugins.push({ name: plugin.name ?? file, ...plugin });
    }
  }
  return plugins;
}

export async function runHook(plugins, hookName, ctx) {
  for (const plugin of plugins) {
    const hook = plugin[hookName];
    if (typeof hook !== 'function') continue;
    await hook(ctx);
    if (ctx.rejected) throw ctx.rejected;
  }
}
