/**
 * @name TuneFlow测试版
 * @version 1.0_beta
 * @author Ryn
 */

'use strict'
const { EVENT_NAMES, request, on, send } = globalThis.lx
const API_BASE = 'https://music.bxa241d4.shop'
const SOURCES = ["kw","kg","tx","wy","mg"]
const QUALITIES = ["128k","320k","flac","flac24bit","hires"]

const http = (url, opts = {}) => new Promise((res, rej) => {
  request(url, opts, (err, resp) => err ? rej(err) : res(resp.body))
})

const getUrl = (src, info, q) => {
  const id = info.hash ?? info.songmid ?? info.id ?? info.songId
  if (!id) return Promise.reject(new Error('Missing ID'))
  return http(API_BASE + '/api/music/url?source=' + src + '&songId=' + encodeURIComponent(id) + '&quality=' + (QUALITIES.includes(q) ? q : QUALITIES[0]))
    .then(b => { const d = typeof b === 'string' ? JSON.parse(b) : b; if (d.code === 200 && d.url) return d.url; throw new Error(d.message || 'Failed') })
}

on(EVENT_NAMES.request, ({ source, action, info }) => {
  if (action === 'musicUrl') return getUrl(source, info.musicInfo, info.type)
  return Promise.reject(new Error('Unsupported action'))
})

send(EVENT_NAMES.inited, { sources: {
    kw: { name: "Kuwo", type: "music", actions: ["musicUrl","lyric","pic"], qualitys: ["128k","320k","flac","flac24bit","hires"] },
    kg: { name: "Kugou", type: "music", actions: ["musicUrl","lyric","pic"], qualitys: ["128k","320k","flac","flac24bit","hires"] },
    tx: { name: "QQMusic", type: "music", actions: ["musicUrl","lyric","pic"], qualitys: ["128k","320k","flac","flac24bit","hires"] },
    wy: { name: "Netease", type: "music", actions: ["musicUrl","lyric","pic"], qualitys: ["128k","320k","flac","flac24bit","hires"] },
    mg: { name: "Migu", type: "music", actions: ["musicUrl","lyric","pic"], qualitys: ["128k","320k","flac","flac24bit","hires"] }
} })
