import AsyncStorage from '@react-native-async-storage/async-storage';
import { AppConfig, AppSettings } from '../types/config';

const SETTINGS_KEY = 'app_settings';
const CONFIG_CACHE_KEY = 'cached_config';

// 默认设置
const DEFAULT_SETTINGS: AppSettings = {
  configFileName: 'config.json',
  serverUrl: '',
};

// 获取设置
export const getSettings = async (): Promise<AppSettings> => {
  try {
    const stored = await AsyncStorage.getItem(SETTINGS_KEY);
    if (stored) {
      return { ...DEFAULT_SETTINGS, ...JSON.parse(stored) };
    }
    return DEFAULT_SETTINGS;
  } catch (error) {
    console.error('获取设置失败:', error);
    return DEFAULT_SETTINGS;
  }
};

// 保存设置
export const saveSettings = async (settings: AppSettings): Promise<void> => {
  try {
    await AsyncStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
  } catch (error) {
    console.error('保存设置失败:', error);
    throw error;
  }
};

// 加载本地配置文件
export const loadLocalConfig = async (): Promise<AppConfig | null> => {
  try {
    // 尝试加载项目根目录下的 config.json 文件
    const localConfig = require('../../config.json');
    console.log('成功加载本地配置文件:', localConfig);

    return localConfig as AppConfig;
  } catch (error) {
    console.log('本地配置文件不存在或加载失败:', error);
    return null;
  }
};

// 从服务器下载配置文件
export const downloadConfig = async (
  serverUrl: string,
  configFileName: string,
): Promise<AppConfig> => {
  try {
    const url = `${serverUrl.replace(/\/$/, '')}/${configFileName}.json`;
    console.log('下载配置文件:', url);

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const config: AppConfig = await response.json();

    // 缓存服务器配置文件（标记为服务器来源）
    const configWithSource = { ...config, _source: 'server' };
    await AsyncStorage.setItem(
      CONFIG_CACHE_KEY,
      JSON.stringify(configWithSource),
    );

    return config;
  } catch (error) {
    console.error('下载配置文件失败:', error);
    throw error;
  }
};

// 获取缓存的配置文件
export const getCachedConfig = async (): Promise<AppConfig | null> => {
  try {
    const cached = await AsyncStorage.getItem(CONFIG_CACHE_KEY);
    if (cached) {
      const config = JSON.parse(cached);
      // 移除内部标记字段
      delete config._source;
      return config;
    }
    return null;
  } catch (error) {
    console.error('获取缓存配置失败:', error);
    return null;
  }
};

// 获取配置文件（优先级：缓存的服务器配置 > 本地config.json > 空数据）
export const getConfig = async (): Promise<AppConfig | null> => {
  try {
    // 1. 先尝试获取缓存的配置（通常是从服务器下载的）
    const cachedConfig = await getCachedConfig();
    if (cachedConfig) {
      console.log('使用缓存的配置文件');
      return cachedConfig;
    }

    // 2. 如果没有缓存，尝试加载本地配置文件
    const localConfig = await loadLocalConfig();
    if (localConfig) {
      console.log('使用本地 config.json 文件');
      // 将本地配置也缓存起来，但标记为本地来源
      const configWithSource = { ...localConfig, _source: 'local' };
      await AsyncStorage.setItem(
        CONFIG_CACHE_KEY,
        JSON.stringify(configWithSource),
      );
      return localConfig;
    }

    console.log('没有找到任何配置文件');
    return null;
  } catch (error) {
    console.error('获取配置文件失败:', error);
    return null;
  }
};

// 清除缓存配置（用于强制重新加载）
export const clearCachedConfig = async (): Promise<void> => {
  try {
    await AsyncStorage.removeItem(CONFIG_CACHE_KEY);
    console.log('已清除缓存配置');
  } catch (error) {
    console.error('清除缓存配置失败:', error);
  }
};

// 向服务器发送任务执行请求
export const executeTask = async (
  serverUrl: string,
  endpoint: string,
  taskData: any,
): Promise<any> => {
  try {
    const url = `${serverUrl.replace(/\/$/, '')}${endpoint}`;
    console.log('执行任务请求:', url, taskData);

    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(taskData),
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    return await response.json();
  } catch (error) {
    console.error('执行任务失败:', error);
    throw error;
  }
};
