/**
 * 频道检测结果缓存
 * 避免每次打开都重复检测
 */

const CACHE_KEY = 'iptv_channel_cache'
const CACHE_VERSION = '1.0'
const DEFAULT_EXPIRE = 24 * 60 * 60 * 1000 // 默认缓存24小时

// 获取缓存
export function getCachedChannels() {
  try {
    const saved = localStorage.getItem(CACHE_KEY)
    if (!saved) return null
    
    const { version, timestamp, data } = JSON.parse(saved)
    
    // 版本检查
    if (version !== CACHE_VERSION) {
      console.log('[Cache] 版本过期，清除缓存')
      clearCache()
      return null
    }
    
    // 过期检查（使用用户配置的过期时间）
    const expireTime = parseInt(localStorage.getItem('iptv_cache_expire')) || DEFAULT_EXPIRE
    const age = Date.now() - timestamp
    if (age > expireTime) {
      console.log('[Cache] 缓存已过期，年龄:', Math.round(age / 1000 / 60), '分钟')
      return null
    }
    
    console.log('[Cache] 命中缓存，年龄:', Math.round(age / 1000 / 60), '分钟，剩余:', Math.round((expireTime - age) / 1000 / 60), '分钟')
    return data
    
  } catch (e) {
    console.error('[Cache] 读取失败:', e)
    return null
  }
}

// 设置缓存
export function setCachedChannels(channels) {
  try {
    const cache = {
      version: CACHE_VERSION,
      timestamp: Date.now(),
      data: channels
    }
    localStorage.setItem(CACHE_KEY, JSON.stringify(cache))
    console.log('[Cache] 已保存', channels.length, '个频道')
  } catch (e) {
    console.error('[Cache] 保存失败:', e)
  }
}

// 清除缓存
export function clearCache() {
  localStorage.removeItem(CACHE_KEY)
  console.log('[Cache] 已清除')
}

// 检查是否有有效缓存
export function hasValidCache() {
  return getCachedChannels() !== null
}

// 获取缓存信息
export function getCacheInfo() {
  try {
    const saved = localStorage.getItem(CACHE_KEY)
    if (!saved) return null
    
    const { timestamp } = JSON.parse(saved)
    const expireTime = parseInt(localStorage.getItem('iptv_cache_expire')) || DEFAULT_EXPIRE
    const age = Date.now() - timestamp
    const remaining = expireTime - age
    
    return {
      age: Math.max(0, Math.round(age / 1000 / 60)), // 已缓存分钟数
      remaining: Math.max(0, Math.round(remaining / 1000 / 60)), // 剩余分钟数
      isValid: remaining > 0
    }
  } catch {
    return null
  }
}
