/**
 * @name HYWmusic_beta
 * @version 0.41.0
 * @author Ryn
 * @description HYWmusic LX Music 音源脚本
 * @homepage https://github.com/Macrohard0001/HYWmusic_source
 * @license MIT
 *
 * 支持平台: 酷我音乐、咪咕音乐、酷狗音乐、QQ音乐、网易云音乐
 * 生成时间: 2026-06-04T14:15:15.850Z
 */

'use strict'

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

const API_BASE = 'http://103.79.184.141:3000' || 'https://hywmusic.example.com'
const SUPPORTED_SOURCES = ["kw","kg","tx","wy","mg"]
const ALLOWED_QUALITIES = ['128k', '320k', 'flac']
const CARD_KEY = ''
const SCRIPT_VERSION = 'HYWmusic_beta_v0.41.0'

// ========== HTTP 请求封装 ==========
const httpRequest = (url) => new Promise((resolve, reject) => {
  const headers = {
    'X-Script-Version': SCRIPT_VERSION,
  }
  if (CARD_KEY) headers['X-Card-Key'] = CARD_KEY

  request(url, { headers }, (err, resp) => {
    if (err) return reject(new Error('网络请求失败'))
    resolve(resp.body)
  })
})

const apiRequest = async (endpoint, params = {}) => {
  const query = Object.entries(params)
    .filter(([, v]) => v !== undefined && v !== null && v !== '')
    .map(([k, v]) => k + '=' + encodeURIComponent(v))
    .join('&')
  const url = API_BASE + endpoint + (query ? '?' + query : '')

  const body = await httpRequest(url)
  const data = typeof body === 'string' ? JSON.parse(body) : body

  if (data.code === 401 || data.code === 403) throw new Error('无访问权限')
  if (data.code !== 200) throw new Error('请求失败')
  return data
}

// 获取歌曲ID - 兼容各种字段名
const getSongId = (musicInfo) =>
  musicInfo.songmid || musicInfo.songId || musicInfo.id || musicInfo.hash || musicInfo.rid || musicInfo.musicId || musicInfo.copyrightId || musicInfo.songid

// ========== 核心功能 ==========

const getMusicUrl = async (source, musicInfo, quality) => {
  if (!SUPPORTED_SOURCES.includes(source)) return Promise.reject(new Error('不支持的平台'))
  const songId = getSongId(musicInfo)
  if (!songId) return Promise.reject(new Error('歌曲ID不存在'))

  const data = await apiRequest('/api/music/url', { source, songId, quality })
  if (data.url) return data.url
  throw new Error('获取音乐链接失败')
}

const getLyric = async (source, musicInfo) => {
  const songId = getSongId(musicInfo)
  if (!songId) return { lyric: '', tlyric: '', rlyric: '', lxlyric: '' }
  try {
    const data = await apiRequest('/api/music/info', { action: 'lyric', source, songId })
    return data.data || { lyric: '', tlyric: '', rlyric: '', lxlyric: '' }
  } catch (e) { return { lyric: '', tlyric: '', rlyric: '', lxlyric: '' } }
}

const getPic = async (source, musicInfo) => {
  const songId = getSongId(musicInfo)
  if (!songId) return ''
  try {
    const data = await apiRequest('/api/music/info', { action: 'pic', source, songId })
    return data.data?.pic || ''
  } catch (e) { return '' }
}

// ========== 事件注册 ==========
on(EVENT_NAMES.request, ({ source, action, info }) => {
  switch (action) {
    case 'musicUrl': return getMusicUrl(source, info.musicInfo, info.type)
    case 'lyric': return getLyric(source, info.musicInfo)
    case 'pic': return getPic(source, info.musicInfo)
  }
})

send(EVENT_NAMES.inited, {
  sources: {"kw":{"name":"酷我音乐","type":"music","actions":["musicUrl"],"qualitys":["128k","320k","flac"]},"kg":{"name":"酷狗音乐","type":"music","actions":["musicUrl"],"qualitys":["128k","320k","flac"]},"tx":{"name":"QQ音乐","type":"music","actions":["musicUrl"],"qualitys":["128k","320k","flac"]},"wy":{"name":"网易云音乐","type":"music","actions":["musicUrl"],"qualitys":["128k","320k","flac"]},"mg":{"name":"咪咕音乐","type":"music","actions":["musicUrl"],"qualitys":["128k","320k","flac"]}}
})
