/**
 * EPG 数据获取和解析
 * 支持 XMLTV 格式
 */

const EPG_CACHE_KEY = 'iptv_epg_cache'
const EPG_CACHE_TIME = 1000 * 60 * 60 * 2 // 2小时缓存

// 获取 EPG 数据
export async function fetchEPG(url) {
  // 先检查缓存
  const cached = getEPGCache()
  if (cached) {
    console.log('[EPG] 使用缓存数据')
    return cached
  }
  
  try {
    const response = await fetch(url)
    const xmlText = await response.text()
    const epgData = parseEPGXML(xmlText)
    
    // 缓存数据
    setEPGCache(epgData)
    
    return epgData
  } catch (e) {
    console.error('[EPG] 获取失败:', e)
    return null
  }
}

// 解析 XMLTV 格式
export function parseEPGXML(xmlText) {
  const parser = new DOMParser()
  const doc = parser.parseFromString(xmlText, 'text/xml')
  
  const programmes = []
  const programmeNodes = doc.querySelectorAll('programme')
  
  programmeNodes.forEach(node => {
    const programme = {
      channel: node.getAttribute('channel'),
      start: parseXMLTVTime(node.getAttribute('start')),
      stop: parseXMLTVTime(node.getAttribute('stop')),
      title: getTextContent(node, 'title'),
      desc: getTextContent(node, 'desc'),
      category: getTextContent(node, 'category'),
      icon: getAttribute(node, 'icon', 'src')
    }
    programmes.push(programme)
  })
  
  // 按频道分组
  const epgByChannel = {}
  programmes.forEach(p => {
    if (!epgByChannel[p.channel]) {
      epgByChannel[p.channel] = []
    }
    epgByChannel[p.channel].push(p)
  })
  
  // 每个频道按时间排序
  Object.keys(epgByChannel).forEach(channel => {
    epgByChannel[channel].sort((a, b) => a.start - b.start)
  })
  
  return epgByChannel
}

// 解析 XMLTV 时间格式: 20240104120000 +0800
function parseXMLTVTime(timeStr) {
  if (!timeStr) return null
  
  // 提取年月日时分秒
  const year = timeStr.substring(0, 4)
  const month = timeStr.substring(4, 6)
  const day = timeStr.substring(6, 8)
  const hour = timeStr.substring(8, 10)
  const minute = timeStr.substring(10, 12)
  const second = timeStr.substring(12, 14)
  
  return new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`)
}

function getTextContent(node, tagName) {
  const child = node.querySelector(tagName)
  return child?.textContent?.trim() || ''
}

function getAttribute(node, tagName, attrName) {
  const child = node.querySelector(tagName)
  return child?.getAttribute(attrName) || ''
}

// 缓存管理
function getEPGCache() {
  try {
    const cached = localStorage.getItem(EPG_CACHE_KEY)
    if (!cached) return null
    
    const { data, timestamp } = JSON.parse(cached)
    if (Date.now() - timestamp > EPG_CACHE_TIME) {
      localStorage.removeItem(EPG_CACHE_KEY)
      return null
    }
    
    // 恢复 Date 对象
    Object.keys(data).forEach(channel => {
      data[channel].forEach(p => {
        p.start = new Date(p.start)
        p.stop = new Date(p.stop)
      })
    })
    
    return data
  } catch {
    return null
  }
}

function setEPGCache(data) {
  try {
    localStorage.setItem(EPG_CACHE_KEY, JSON.stringify({
      data,
      timestamp: Date.now()
    }))
  } catch (e) {
    console.error('[EPG] 缓存失败:', e)
  }
}

// 清空缓存
export function clearEPGCache() {
  localStorage.removeItem(EPG_CACHE_KEY)
}

// 获取当前节目
export function getCurrentProgramme(epgList) {
  if (!epgList || epgList.length === 0) return null
  const now = new Date()
  return epgList.find(p => now >= p.start && now < p.stop)
}

// 获取下一个节目
export function getNextProgramme(epgList) {
  if (!epgList || epgList.length === 0) return null
  const now = new Date()
  return epgList.find(p => p.start > now)
}

// 获取今日节目列表
export function getTodayProgrammes(epgList) {
  if (!epgList || epgList.length === 0) return []
  const now = new Date()
  return epgList.filter(p => {
    const pDate = new Date(p.start)
    return pDate.getDate() === now.getDate() &&
           pDate.getMonth() === now.getMonth() &&
           pDate.getFullYear() === now.getFullYear()
  })
}

// 计算节目进度百分比
export function getProgrammeProgress(programme) {
  if (!programme) return 0
  const now = new Date()
  const total = programme.stop - programme.start
  const elapsed = now - programme.start
  return Math.min(100, Math.max(0, (elapsed / total) * 100))
}

// 格式化时间
export function formatTime(date) {
  if (!date) return ''
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 格式化日期
export function formatDate(date) {
  if (!date) return ''
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const pDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
  
  const diffDays = (pDate - today) / (1000 * 60 * 60 * 24)
  
  if (diffDays === 0) return '今天'
  if (diffDays === 1) return '明天'
  if (diffDays === -1) return '昨天'
  
  return date.toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric'
  })
}
