import { ref, computed, onMounted } from "vue";
import { useStorage } from "./useStorage.js";

// 全局状态
const channels = ref([]);
const loading = ref(false);
let initialized = false;

export function useChannels() {
  const storage = useStorage();

  // 分组列表（基于频道计算）
  const groups = computed(() => {
    return [...new Set(channels.value.map((c) => c.group))];
  });

  // 加载频道数据
  const loadChannels = async (force = false) => {
    if (loading.value) return;
    loading.value = true;

    try {
      // 检查缓存
      if (!force) {
        const isValid = await storage.isListCacheValid();
        if (isValid) {
          const cached = await storage.getChannels();
          if (cached && cached.length > 0) {
            channels.value = cached;
            loading.value = false;
            // 后台刷新
            refreshChannelsInBackground();
            return;
          }
        }
      }

      // 从网络加载
      const text = await fetchChannelData();
      if (text && !text.startsWith("ERROR")) {
        const parsed = parseChannelData(text);
        channels.value = parsed;
        await storage.setChannels(parsed);
      }
    } finally {
      loading.value = false;
    }
  };

  // 后台刷新频道
  const refreshChannelsInBackground = async () => {
    try {
      const text = await fetchChannelData();
      if (text && !text.startsWith("ERROR")) {
        const parsed = parseChannelData(text);
        if (parsed.length > 0) {
          channels.value = parsed;
          await storage.setChannels(parsed);
        }
      }
    } catch (e) {
      console.error("后台刷新失败:", e);
    }
  };

  // 获取频道数据（网络）
  const fetchChannelData = async () => {
    const platform = import.meta.env.VITE_PLATFORM || "web";

    // Android/TV 使用原生接口
    if ((platform === "android" || platform === "tv") && window.AndroidAsset) {
      try {
        return window.AndroidAsset.readChannelData();
      } catch (e) {
        console.error("读取本地数据失败:", e);
      }
    }

    // Web/Desktop 从网络加载
    try {
      const response = await fetch(
        "https://cdn.jsdelivr.net/gh/Guovin/iptv-api@gd/output/result.txt"
      );
      if (response.ok) {
        return await response.text();
      }
    } catch (e) {
      console.error("网络加载失败:", e);
    }

    return null;
  };

  // 解析频道数据
  const parseChannelData = (text) => {
    const result = [];
    const lines = text.split("\n");
    let currentGroup = "";

    for (const line of lines) {
      const trimmed = line.trim();
      if (!trimmed) continue;

      if (trimmed.includes("#genre#")) {
        currentGroup = trimmed.split(",")[0];
      } else if (trimmed.includes(",")) {
        const [name, url] = trimmed.split(",").map((s) => s.trim());
        if (name && url) {
          const existing = result.find(
            (c) => c.name === name && c.group === currentGroup
          );
          if (existing) {
            existing.urls.push(url);
          } else {
            result.push({
              id: `${currentGroup}_${name}`,
              name,
              group: currentGroup,
              urls: [url],
              logo: "",
              epgId: "",
            });
          }
        }
      }
    }

    return result;
  };

  // 根据索引获取频道
  const getChannelByIndex = (index) => {
    return channels.value[index] || null;
  };

  // 初始化加载
  onMounted(() => {
    if (!initialized) {
      loadChannels();
      initialized = true;
    }
  });

  return {
    channels,
    groups,
    loading,
    loadChannels,
    getChannelByIndex,
  };
}
