/**
 * @name HYWmusic_刚毅临时源（测试
 * @version 0.0.1_去你m的煞笔q音
 * @author Ryn
 * @description HYWmusic LX Music 音源脚本
 * @homepage https://github.com/Macrohard0001/HYWmusic_source
 * @license MIT
 * @updateUrl http://103.79.184.141:3000/api/releases/check-update?script=HYWmusic_%E5%88%9A%E6%AF%85%E4%B8%B4%E6%97%B6%E6%BA%90%EF%BC%88%E6%B5%8B%E8%AF%95
 *
 * 支持平台: 酷我音乐、咪咕音乐、酷狗音乐、QQ音乐、网易云音乐
 * 生成时间: 2026-06-20T07:32:33.934Z
 */

'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 = ["wy"]
const ALLOWED_QUALITIES = ['128k', '320k', 'flac']
const CARD_KEY = 'U7NR-7IKF-SETI-X5EW'
const SCRIPT_VERSION = 'HYWmusic_刚毅临时源（测试_v0.0.1_去你m的煞笔q音'
const SCRIPT_NAME = 'HYWmusic_刚毅临时源（测试'
const CURRENT_VERSION = '0.0.1_去你m的煞笔q音'
const UPDATE_URL = API_BASE + '/api/releases/check-update?script=' + encodeURIComponent(SCRIPT_NAME)

// ========== 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 '' }
}

// ========== 检查更新功能 ==========
// LX Music 官方规范：脚本需要处理 checkUpdate 事件来响应更新检查
on(EVENT_NAMES.checkUpdate, async () => {
  try {
    // 从服务端获取最新版本信息
    const response = await httpRequest(UPDATE_URL)
    const data = typeof response === 'string' ? JSON.parse(response) : response
    
    if (data.code === 200 && data.data) {
      const latestVersion = data.data.version
      const updateLog = data.data.updateLog || ''
      
      // 比较版本号
      const isNewer = compareVersions(latestVersion, CURRENT_VERSION) > 0
      
      if (isNewer) {
        // 返回更新信息
        return {
          haveUpdate: true,
          version: latestVersion,
          log: updateLog,
          downloadUrl: API_BASE + '/api/releases/download?name=' + encodeURIComponent(SCRIPT_NAME) + '&version=' + latestVersion,
        }
      }
    }
    
    // 没有更新
    return {
      haveUpdate: false,
      version: CURRENT_VERSION,
      log: '',
    }
  } catch (e) {
    // 检查更新失败，返回当前版本信息
    return {
      haveUpdate: false,
      version: CURRENT_VERSION,
      log: '',
    }
  }
})

// 版本号比较函数
function compareVersions(v1, v2) {
  const parts1 = v1.split('.').map(Number)
  const parts2 = v2.split('.').map(Number)
  
  for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
    const p1 = parts1[i] || 0
    const p2 = parts2[i] || 0
    if (p1 > p2) return 1
    if (p1 < p2) return -1
  }
  return 0
}

// ========== 事件注册 ==========
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: {"wy":{"name":"网易云音乐","type":"music","actions":["musicUrl"],"qualitys":["128k","320k","flac"]}}
})
