const { logToFile } = require('./logger');

function parseInstances(envVar, legacyUrl, legacyKey, legacyUsername, legacyPassword) {
  // Try to parse JSON array format first
  if (envVar) {
    try {
      // Handle multi-line JSON by removing newlines and extra spaces
      const cleaned = envVar.replace(/\s+/g, ' ').trim();
      const instances = JSON.parse(cleaned);
      if (Array.isArray(instances) && instances.length > 0) {
        logToFile(`[Config] Parsed ${instances.length} instances from JSON array`);
        return instances.map((inst, idx) => ({
          ...inst,
          id: inst.name || `instance-${idx + 1}`
        }));
      }
    } catch (err) {
      logToFile(`[Config] Failed to parse JSON array: ${err.message}`);
    }
  }
  
  // Fall back to legacy single-instance format
  if (legacyUrl && legacyKey) {
    logToFile(`[Config] Using legacy single-instance format`);
    return [{
      id: 'default',
      name: 'Default',
      url: legacyUrl,
      apiKey: legacyKey,
      username: legacyUsername,
      password: legacyPassword
    }];
  }
  
  return [];
}

function getSABnzbdInstances() {
  return parseInstances(
    process.env.SABNZBD_INSTANCES,
    process.env.SABNZBD_URL,
    process.env.SABNZBD_API_KEY
  );
}

function getSonarrInstances() {
  return parseInstances(
    process.env.SONARR_INSTANCES,
    process.env.SONARR_URL,
    process.env.SONARR_API_KEY
  );
}

function getRadarrInstances() {
  return parseInstances(
    process.env.RADARR_INSTANCES,
    process.env.RADARR_URL,
    process.env.RADARR_API_KEY
  );
}

function getQbittorrentInstances() {
  return parseInstances(
    process.env.QBITTORRENT_INSTANCES,
    process.env.QBITTORRENT_URL,
    null, // no apiKey for qBittorrent
    process.env.QBITTORRENT_USERNAME,
    process.env.QBITTORRENT_PASSWORD
  );
}

module.exports = {
  getSABnzbdInstances,
  getSonarrInstances,
  getRadarrInstances,
  getQbittorrentInstances,
  parseInstances
};
