const fs = require('fs');
const path = require('path');

const PROVIDERS_DIR = path.join(__dirname, '..', 'providers');

function listAll() {
  return fs
    .readdirSync(PROVIDERS_DIR)
    .filter((f) => f.endsWith('.js'))
    .map((f) => f.slice(0, -3))
    .sort();
}

function loadProviders(names) {
  const providers = [];
  const loadErrors = {};
  for (const name of names) {
    const file = path.join(PROVIDERS_DIR, `${name}.js`);
    if (!fs.existsSync(file)) {
      loadErrors[name] = 'not found';
      continue;
    }
    try {
      const mod = require(file);
      if (typeof mod.getStreams !== 'function') {
        loadErrors[name] = 'does not export getStreams()';
        continue;
      }
      providers.push({ name, getStreams: mod.getStreams });
    } catch (err) {
      loadErrors[name] = err.message.split('\n')[0];
    }
  }
  return { providers, loadErrors };
}

module.exports = { listAll, loadProviders, PROVIDERS_DIR };
