// Background Service Worker
import { backgroundHandler } from '../shared/messaging.js';
import { dictionaryManager, bingDictionary } from '../shared/dictionary/index.js';

console.log('[SaladDict] Background service worker started');

// 监听安装事件
chrome.runtime.onInstalled.addListener((details) => {
  console.log('[SaladDict] Extension installed:', details.reason);
});

// BackgroundHandler 自动初始化消息监听
console.log('[SaladDict] Message handler initialized');

// 注册词典到管理器
dictionaryManager.register('bing', bingDictionary);
console.log('[SaladDict] Registered dictionaries:', dictionaryManager.getNames());

// 注册词典查询处理器
backgroundHandler.register('DICT.SEARCH', async (payload) => {
  const { word, dictNames = [] } = payload;
  
  console.log('[Background] DICT.SEARCH:', word, dictNames);
  
  try {
    const { results, errors } = await dictionaryManager.search(word, dictNames);
    
    console.log('[Background] Search results:', results);
    if (errors.length > 0) {
      console.warn('[Background] Search errors:', errors);
    }
    
    return { results, errors };
  } catch (error) {
    console.error('[Background] Search failed:', error);
    throw error;
  }
});

// 注册获取词典列表处理器
backgroundHandler.register('DICT.GET_LIST', async () => {
  const dictionaries = dictionaryManager.getAll().map(({ name, dictionary }) => ({
    name,
    info: dictionary.getInfo()
  }));
  
  return { dictionaries };
});

console.log('[SaladDict] Message handlers registered');
