/**
 * @name 念心音源
 * @description 音源更新，关注微信公众号: 念心小站
 * @version 1.0.0
 * @author 念心小站
 * @mail 微信公众号: 念心小站
 * @homepage 微信公众号: 念心小站
 * @update_url https://gitee.com/nianxinxz1/emo-music/raw/master/wubian.json
 */
const { EVENT_NAMES, on, send } = globalThis.lx

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

const API_PATHS = {
    kg: '/kgqq/kg.php',
    tx: '/kgqq/tx.php',
    wy: '/wy.php',
    kw: '/kw.php',
    mg: '/mg.php',
}

const SUPPORTED_QUALITIES = {
    kg: ['128k', '320k', 'flac'],
    tx: ['128k', '320k', 'flac'],
    wy: ['128k', '320k', 'flac'],
    kw: ['128k', '320k', 'flac'],
    mg: ['128k', '320k'],
}

const getSongId = (source, { hash, songmid, id, rid }) =>
    ({
        kg: hash || songmid || id,
        tx: songmid || id,
        wy: id,
        kw: rid || id,
        mg: id,
    })[source] || id || songmid || hash

const getMusicUrl = (source, info, quality = '128k') => {
    const mappedQuality = QUALITY_MAP[quality]
    if (!mappedQuality) return Promise.reject(new Error(`音质 ${quality} 不支持`))

    const songId = getSongId(source, info)
    if (!songId) return Promise.reject(new Error('找不到歌曲ID'))

    const path = API_PATHS[source]
    if (!path) return Promise.reject(new Error(`不支持的平台: ${source}`))

    const url = `https://music.nxinxz.com${path}?id=${encodeURIComponent(songId)}&level=${encodeURIComponent(mappedQuality)}&type=mp3`
    return Promise.resolve(url)
}

on(EVENT_NAMES.request, ({ source, action, info }) => {
    if (action !== 'musicUrl') return Promise.reject(new Error('仅支持musicUrl操作'))
    if (!API_PATHS[source]) return Promise.reject(new Error(`不支持的平台: ${source}`))
    if (!info?.musicInfo) return Promise.reject(new Error('缺少歌曲信息'))

    return getMusicUrl(source, info.musicInfo, info.type || '128k')
})

send(EVENT_NAMES.inited, {
    openDevTools: false,
    sources: Object.fromEntries(
        Object.entries(SUPPORTED_QUALITIES).map(([key, qualitys]) => [
            key,
            { type: 'music', actions: ['musicUrl'], qualitys },
        ])
    ),
})

console.log('[念心音源] 初始化完成')