/**
 * @file 词典管理器
 * @description 管理多个词典实例，支持注册、查询和获取词典列表
 */

import { DictionaryBase } from './base.js';

/**
 * 词典管理器类
 * 负责管理所有词典实例的注册和查询
 */
class DictionaryManager {
  constructor() {
    /** @type {Map<string, DictionaryBase>} */
    this.dictionaries = new Map();
  }

  /**
   * 注册词典实例
   * @param {string} name - 词典唯一标识名
   * @param {DictionaryBase} dictionaryInstance - 词典实例
   * @throws {Error} 名称不能为空或实例必须继承 DictionaryBase
   */
  register(name, dictionaryInstance) {
    if (!name || typeof name !== 'string') {
      throw new Error('Dictionary name must be a non-empty string');
    }

    if (!(dictionaryInstance instanceof DictionaryBase)) {
      throw new Error('Dictionary instance must extend DictionaryBase');
    }

    this.dictionaries.set(name, dictionaryInstance);
  }

  /**
   * 取消注册词典
   * @param {string} name - 词典名称
   * @returns {boolean} 是否成功移除
   */
  unregister(name) {
    return this.dictionaries.delete(name);
  }

  /**
   * 获取指定名称的词典
   * @param {string} name - 词典名称
   * @returns {DictionaryBase|undefined} 词典实例
   */
  get(name) {
    return this.dictionaries.get(name);
  }

  /**
   * 获取所有已注册的词典
   * @returns {Array<{name: string, dictionary: DictionaryBase}>} 词典列表
   */
  getAll() {
    const result = [];
    for (const [name, dictionary] of this.dictionaries) {
      result.push({ name, dictionary });
    }
    return result;
  }

  /**
   * 获取所有词典名称列表
   * @returns {Array<string>} 词典名称数组
   */
  getNames() {
    return Array.from(this.dictionaries.keys());
  }

  /**
   * 查询单词
   * @param {string} word - 要查询的单词
   * @param {Array<string>} [dictNames] - 指定查询的词典名称列表，不传则查询所有
   * @returns {Promise<Object>} 查询结果 {results: Array<{name: string, result: DictionaryResult}>, errors: Array<{name: string, error: string}>}
   */
  async search(word, dictNames = []) {
    if (!word || typeof word !== 'string' || !word.trim()) {
      throw new Error('Search word must be a non-empty string');
    }

    const targetNames = dictNames.length > 0 
      ? dictNames.filter(name => this.dictionaries.has(name))
      : this.getNames();

    const results = [];
    const errors = [];

    // 并行查询所有目标词典
    const promises = targetNames.map(async (name) => {
      const dictionary = this.dictionaries.get(name);
      try {
        const result = await dictionary.search(word.trim());
        results.push({ name, result });
      } catch (error) {
        errors.push({ 
          name, 
          error: error instanceof Error ? error.message : String(error) 
        });
      }
    });

    await Promise.all(promises);

    return { results, errors };
  }

  /**
   * 检查词典是否已注册
   * @param {string} name - 词典名称
   * @returns {boolean} 是否已注册
   */
  has(name) {
    return this.dictionaries.has(name);
  }

  /**
   * 获取已注册词典数量
   * @returns {number} 词典数量
   */
  get count() {
    return this.dictionaries.size;
  }

  /**
   * 清空所有词典
   */
  clear() {
    this.dictionaries.clear();
  }
}

// 导出单例实例
export const dictionaryManager = new DictionaryManager();

// 导出类，方便需要时创建新实例
export { DictionaryManager };
