/*!
 * @name 闻音音源
 * @description 无需解密，最高支持到hires
 * @version v1.1
 * @author 竹佀
 */

const { EVENT_NAMES, on, send } = globalThis.lx

const QUALITY_MAP = {
  '128k': 'standard',
  '320k': 'exhigh',
  'flac': 'lossless',
  'flac24bit': 'hires',
  'hires': 'zp'
}

const BASE_URL = 'https://kw-api.cenguigui.cn'

function getSongId(musicInfo) {
  return musicInfo.hash || musicInfo.songmid || musicInfo.id || musicInfo.rid || musicInfo.mid
}

on(EVENT_NAMES.request, ({ source, action, info }) => {
  if (source !== 'kw' || action !== 'musicUrl') return Promise.reject(new Error('不支持的操作'))
  if (!info || !info.musicInfo) return Promise.reject(new Error('缺少音乐信息'))
  
  const musicInfo = info.musicInfo
  const quality = info.type || '320k'
  const apiQuality = QUALITY_MAP[quality] || 'exhigh'
  
  const songId = getSongId(musicInfo)
  if (!songId) return Promise.reject(new Error('无法获取歌曲ID'))
  
  const audioUrl = `${BASE_URL}?id=${songId}&type=song&level=${apiQuality}&format=mp3`
  
  return Promise.resolve(audioUrl)
})

send(EVENT_NAMES.inited, {
  openDevTools: false,
  sources: {
    kw: {
      name: '酷我音乐 - 小黄API',
      type: 'music',
      actions: ['musicUrl'],
      qualitys: ['128k', '320k', 'flac', 'flac24bit', 'hires']
    }
  }
})<