/**
 * IPTV-API TXT 格式解析器
 * 
 * 格式：
 * 分组名,#genre#
 * 频道名,接口地址
 * 频道名,接口地址
 * 
 * 空行分隔不同分组
 */

export function parseTXT(content) {
  const lines = content.split('\n').map(l => l.trim()).filter(l => l)
  const channels = []
  let currentGroup = '默认分组'
  let id = 1

  for (const line of lines) {
    // 分组行：分组名,#genre#
    if (line.includes(',#genre#')) {
      currentGroup = line.split(',')[0].trim()
      continue
    }

    // 频道行：频道名,接口地址
    const commaIndex = line.indexOf(',')
    if (commaIndex === -1) continue

    const name = line.substring(0, commaIndex).trim()
    const url = line.substring(commaIndex + 1).trim()

    // 过滤无效行
    if (!name || !url || !url.startsWith('http')) continue

    channels.push({
      id: String(id++),
      name,
      url,
      group: currentGroup,
      logo: ''
    })
  }

  return channels
}

/**
 * 转换为 M3U 格式
 */
export function convertToM3U(channels) {
  let m3u = '#EXTM3U\n\n'
  
  for (const ch of channels) {
    m3u += `#EXTINF:-1 tvg-name="${ch.name}" tvg-logo="${ch.logo}" group-title="${ch.group}",${ch.name}\n`
    m3u += `${ch.url}\n\n`
  }
  
  return m3u
}
