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

const CONFIG_PATH = path.join(__dirname, '..', 'config.json');

const DEFAULTS = {
  tmdbKey: '',
  enabledProviders: ['videasy', 'vidfast'],
  timeoutMs: 30000,
  apiHost: '0.0.0.0',
  apiPort: 8789,
  filters: {
    minQuality: 'any',
    audioCodec: 'any',
    subtitles: 'any',
    subtitleLang: '',
  },
};

function loadConfig() {
  let cfg = { ...DEFAULTS, filters: { ...DEFAULTS.filters } };
  if (fs.existsSync(CONFIG_PATH)) {
    const saved = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
    cfg = { ...cfg, ...saved, filters: { ...cfg.filters, ...(saved.filters || {}) } };
  } else {
    saveConfig(cfg);
  }
  if (!cfg.tmdbKey && process.env.TMDB_API_KEY) cfg.tmdbKey = process.env.TMDB_API_KEY;
  if (!cfg.tmdbKey) {
    console.error('No TMDB API key found. Set "tmdbKey" in config.json or the TMDB_API_KEY env var.');
    process.exit(1);
  }
  return cfg;
}

function saveConfig(cfg) {
  fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2) + '\n');
}

module.exports = { loadConfig, saveConfig, CONFIG_PATH };
