import { invoke } from '@tauri-apps/api/core';
import {
  SystemVoice,
  SystemVoiceQuery,
  SystemVoiceResponse,
  SystemVoiceStats,
  SystemVoiceType,
  VoiceGender
} from '../types/systemVoice';

/**
 * 系统音色服务
 * 提供系统音色的查询、筛选、搜索等功能
 */
export class SystemVoiceService {
  /**
   * 获取所有活跃的系统音色
   */
  static async getAllSystemVoices(): Promise<SystemVoice[]> {
    try {
      const voices = await invoke<SystemVoice[]>('get_system_voices');
      return voices;
    } catch (error) {
      console.error('获取系统音色列表失败:', error);
      throw new Error(`获取系统音色列表失败: ${error}`);
    }
  }

  /**
   * 根据类型获取系统音色
   */
  static async getSystemVoicesByType(voiceType: SystemVoiceType): Promise<SystemVoice[]> {
    try {
      const voices = await invoke<SystemVoice[]>('get_system_voices_by_type', {
        voice_type: voiceType
      });
      return voices;
    } catch (error) {
      console.error('根据类型获取系统音色失败:', error);
      throw new Error(`根据类型获取系统音色失败: ${error}`);
    }
  }

  /**
   * 根据性别获取系统音色
   */
  static async getSystemVoicesByGender(gender: VoiceGender): Promise<SystemVoice[]> {
    try {
      const voices = await invoke<SystemVoice[]>('get_system_voices_by_gender', {
        gender: gender
      });
      return voices;
    } catch (error) {
      console.error('根据性别获取系统音色失败:', error);
      throw new Error(`根据性别获取系统音色失败: ${error}`);
    }
  }

  /**
   * 根据语言获取系统音色
   */
  static async getSystemVoicesByLanguage(language: string): Promise<SystemVoice[]> {
    try {
      const voices = await invoke<SystemVoice[]>('get_system_voices_by_language', {
        language: language
      });
      return voices;
    } catch (error) {
      console.error('根据语言获取系统音色失败:', error);
      throw new Error(`根据语言获取系统音色失败: ${error}`);
    }
  }

  /**
   * 搜索系统音色
   */
  static async searchSystemVoices(keyword: string): Promise<SystemVoice[]> {
    try {
      const voices = await invoke<SystemVoice[]>('search_system_voices', {
        keyword: keyword
      });
      return voices;
    } catch (error) {
      console.error('搜索系统音色失败:', error);
      throw new Error(`搜索系统音色失败: ${error}`);
    }
  }

  /**
   * 分页获取系统音色
   */
  static async getSystemVoicesPaginated(query: SystemVoiceQuery): Promise<SystemVoiceResponse> {
    try {
      const response = await invoke<SystemVoiceResponse>('get_system_voices_paginated', {
        query: query
      });
      return response;
    } catch (error) {
      console.error('分页获取系统音色失败:', error);
      throw new Error(`分页获取系统音色失败: ${error}`);
    }
  }

  /**
   * 根据voice_id获取系统音色详情
   */
  static async getSystemVoiceById(voiceId: string): Promise<SystemVoice | null> {
    try {
      const voice = await invoke<SystemVoice | null>('get_system_voice_by_id', {
        voiceId: voiceId
      });
      return voice;
    } catch (error) {
      console.error('根据ID获取系统音色失败:', error);
      throw new Error(`根据ID获取系统音色失败: ${error}`);
    }
  }

  /**
   * 检查系统音色是否存在
   */
  static async checkSystemVoiceExists(voiceId: string): Promise<boolean> {
    try {
      const exists = await invoke<boolean>('check_system_voice_exists', {
        voiceId: voiceId
      });
      return exists;
    } catch (error) {
      console.error('检查系统音色是否存在失败:', error);
      throw new Error(`检查系统音色是否存在失败: ${error}`);
    }
  }

  /**
   * 获取系统音色统计信息
   */
  static async getSystemVoiceStats(): Promise<SystemVoiceStats> {
    try {
      const stats = await invoke<SystemVoiceStats>('get_system_voice_stats');
      return stats;
    } catch (error) {
      console.error('获取系统音色统计信息失败:', error);
      throw new Error(`获取系统音色统计信息失败: ${error}`);
    }
  }

  /**
   * 前端筛选系统音色
   * 用于在已加载的音色列表中进行客户端筛选
   */
  static filterVoices(voices: SystemVoice[], query: SystemVoiceQuery): SystemVoice[] {
    return voices.filter(voice => {
      // 类型筛选
      if (query.voice_type && voice.voice_type !== query.voice_type) {
        return false;
      }

      // 性别筛选
      if (query.gender && voice.gender !== query.gender) {
        return false;
      }

      // 语言筛选
      if (query.language && voice.language !== query.language) {
        return false;
      }

      // 关键词搜索
      if (query.keyword) {
        const keyword = query.keyword.toLowerCase();
        const searchText = [
          voice.voice_name,
          voice.voice_name_en,
          voice.description,
          voice.voice_id
        ].filter(Boolean).join(' ').toLowerCase();
        
        if (!searchText.includes(keyword)) {
          return false;
        }
      }

      return true;
    });
  }

  /**
   * 前端排序系统音色
   */
  static sortVoices(voices: SystemVoice[], sortBy: 'name' | 'type' | 'gender' | 'order' = 'order'): SystemVoice[] {
    return [...voices].sort((a, b) => {
      switch (sortBy) {
        case 'name':
          return a.voice_name.localeCompare(b.voice_name);
        case 'type':
          return a.voice_type.localeCompare(b.voice_type);
        case 'gender':
          return a.gender.localeCompare(b.gender);
        case 'order':
        default:
          return a.sort_order - b.sort_order;
      }
    });
  }

  /**
   * 按类型分组系统音色
   */
  static groupVoicesByType(voices: SystemVoice[]): Record<SystemVoiceType, SystemVoice[]> {
    const groups: Record<SystemVoiceType, SystemVoice[]> = {
      [SystemVoiceType.SYSTEM]: [],
      [SystemVoiceType.PREMIUM]: [],
      [SystemVoiceType.CHILD]: [],
      [SystemVoiceType.CHARACTER]: [],
      [SystemVoiceType.HOLIDAY]: [],
      [SystemVoiceType.ENGLISH]: [],
    };

    voices.forEach(voice => {
      // 将字符串类型转换为枚举类型
      const voiceType = voice.voice_type as SystemVoiceType;
      if (groups[voiceType]) {
        groups[voiceType].push(voice);
      }
    });

    return groups;
  }

  /**
   * 按性别分组系统音色
   */
  static groupVoicesByGender(voices: SystemVoice[]): Record<VoiceGender, SystemVoice[]> {
    const groups: Record<VoiceGender, SystemVoice[]> = {
      [VoiceGender.MALE]: [],
      [VoiceGender.FEMALE]: [],
      [VoiceGender.CHILD]: [],
      [VoiceGender.OTHER]: [],
    };

    voices.forEach(voice => {
      if (groups[voice.gender]) {
        groups[voice.gender].push(voice);
      }
    });

    return groups;
  }

  /**
   * 获取推荐音色
   * 根据使用频率、类型等推荐合适的音色
   */
  static getRecommendedVoices(voices: SystemVoice[], limit: number = 6): SystemVoice[] {
    // 简单的推荐逻辑：优先推荐系统音色和精品音色
    const priorityTypes = [SystemVoiceType.SYSTEM, SystemVoiceType.PREMIUM];
    
    const priorityVoices = voices.filter(voice => 
      priorityTypes.includes(voice.voice_type)
    );
    
    const otherVoices = voices.filter(voice => 
      !priorityTypes.includes(voice.voice_type)
    );

    const recommended = [
      ...this.sortVoices(priorityVoices, 'order'),
      ...this.sortVoices(otherVoices, 'order')
    ];

    return recommended.slice(0, limit);
  }
}
