const QUALITY_MIN = { any: 0, '480': 480, '720': 720, '1080': 1080, '2160': 2160 };
const AUDIO_OPTIONS = ['any', 'aac', 'ac3', 'dts', 'opus', 'mp3', 'flac', 'multi'];
const SUBTITLE_OPTIONS = ['any', 'required', 'lang'];

function langCode(lang) {
  return String(lang || '').toLowerCase().replace(/[^a-z]/g, '').slice(0, 2);
}

function hasSubtitleLang(streams_subtitles, wanted) {
  const want = langCode(wanted);
  if (!want) return true;
  return streams_subtitles.some((s) => {
    const code = langCode(s.language) || langCode(s.name);
    return code === want;
  });
}

function applyFilters(streams, filters) {
  const minPixels = QUALITY_MIN[filters.minQuality] ?? 0;
  return streams.filter((s) => {
    if (minPixels > 0 && (s.pixels == null || s.pixels < minPixels)) return false;
    if (filters.audioCodec && filters.audioCodec !== 'any' && s.audio !== filters.audioCodec) return false;
    if (filters.subtitles && filters.subtitles !== 'any') {
      if (s.subtitles.length === 0) return false;
      if (filters.subtitles === 'lang' && filters.subtitleLang && !hasSubtitleLang(s.subtitles, filters.subtitleLang)) return false;
    }
    return true;
  });
}

function rankStreams(streams) {
  return streams
    .slice()
    .sort((a, b) => (b.pixels || 0) - (a.pixels || 0) || a.provider.localeCompare(b.provider));
}

module.exports = { applyFilters, rankStreams, QUALITY_MIN, AUDIO_OPTIONS, SUBTITLE_OPTIONS };
