/**
 * @file 配置管理模块
 * @description 统一的配置读写和监听接口
 */

const STORAGE_KEY = 'salad_config';

const DEFAULT_CONFIG = {
  general: {
    enableSelection: true
  }
};

/**
 * 深度合并对象
 */
function deepMerge(target, source) {
  const result = { ...target };
  for (const key in source) {
    if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
      result[key] = deepMerge(result[key] || {}, source[key]);
    } else {
      result[key] = source[key];
    }
  }
  return result;
}

/**
 * 根据路径获取对象值
 * @param {Object} obj - 对象
 * @param {string} path - 路径，如 'general.enableSelection'
 * @returns {any}
 */
function getByPath(obj, path) {
  const keys = path.split('.');
  let value = obj;
  for (const key of keys) {
    if (value === null || value === undefined) return undefined;
    value = value[key];
  }
  return value;
}

/**
 * 根据路径设置对象值
 * @param {Object} obj - 对象
 * @param {string} path - 路径
 * @param {any} value - 值
 */
function setByPath(obj, path, value) {
  const keys = path.split('.');
  let target = obj;
  for (let i = 0; i < keys.length - 1; i++) {
    const key = keys[i];
    if (!(key in target) || typeof target[key] !== 'object') {
      target[key] = {};
    }
    target = target[key];
  }
  target[keys[keys.length - 1]] = value;
}

/**
 * 配置管理器
 */
export const ConfigManager = {
  /**
   * 获取完整配置
   * @returns {Promise<Object>}
   */
  async getConfig() {
    try {
      const result = await chrome.storage.local.get(STORAGE_KEY);
      return deepMerge(DEFAULT_CONFIG, result[STORAGE_KEY] || {});
    } catch (error) {
      console.error('[ConfigManager] Failed to get config:', error);
      return DEFAULT_CONFIG;
    }
  },

  /**
   * 保存完整配置
   * @param {Object} config
   */
  async saveConfig(config) {
    try {
      await chrome.storage.local.set({ [STORAGE_KEY]: config });
    } catch (error) {
      console.error('[ConfigManager] Failed to save config:', error);
    }
  },

  /**
   * 获取指定配置项
   * @param {string} path - 路径，如 'general.enableSelection'
   * @param {any} defaultValue - 默认值
   * @returns {Promise<any>}
   */
  async get(path, defaultValue) {
    const config = await this.getConfig();
    const value = getByPath(config, path);
    return value !== undefined ? value : defaultValue;
  },

  /**
   * 设置指定配置项
   * @param {string} path - 路径
   * @param {any} value - 值
   */
  async set(path, value) {
    const config = await this.getConfig();
    setByPath(config, path, value);
    await this.saveConfig(config);
  },

  /**
   * 监听配置变更
   * @param {Function} callback - 回调函数(changes, newConfig)
   * @returns {Function} 取消监听的函数
   */
  onChange(callback) {
    const handler = (changes) => {
      if (changes[STORAGE_KEY]) {
        const newValue = changes[STORAGE_KEY].newValue;
        const oldValue = changes[STORAGE_KEY].oldValue;
        callback(newValue, oldValue);
      }
    };
    chrome.storage.onChanged.addListener(handler);
    
    // 返回取消监听的函数
    return () => chrome.storage.onChanged.removeListener(handler);
  }
};

/**
 * 快速检查划词功能是否启用
 * @returns {Promise<boolean>}
 */
export async function isSelectionEnabled() {
  return ConfigManager.get('general.enableSelection', true);
}
