import { invoke } from '@tauri-apps/api/core';
import {
  AnalyzeImageRequest,
  AnalyzeImageResponse,
  SearchRequest,
  SearchResponse,
  LLMQueryRequest,
  LLMQueryResponse,
  SearchConfig,
  OutfitSearchConfigInfo,
} from '../types/outfitSearch';

/**
 * 服装搭配搜索API服务
 * 遵循 Tauri 开发规范的API服务设计原则
 */
export class OutfitSearchService {
  /**
   * 分析服装图像
   */
  static async analyzeOutfitImage(request: AnalyzeImageRequest): Promise<AnalyzeImageResponse> {
    try {
      const response = await invoke<AnalyzeImageResponse>('analyze_outfit_image', { request });
      return response;
    } catch (error) {
      console.error('Failed to analyze outfit image:', error);
      throw new Error(`图像分析失败: ${error}`);
    }
  }

  /**
   * 搜索相似服装
   */
  static async searchSimilarOutfits(request: SearchRequest): Promise<SearchResponse> {
    try {
      const response = await invoke<SearchResponse>('search_similar_outfits', { request });
      return response;
    } catch (error) {
      console.error('Failed to search similar outfits:', error);
      throw new Error(`搜索失败: ${error}`);
    }
  }

  /**
   * LLM问答
   */
  static async askLLMOutfitAdvice(request: LLMQueryRequest): Promise<LLMQueryResponse> {
    try {
      const response = await invoke<LLMQueryResponse>('ask_llm_outfit_advice', { request });
      return response;
    } catch (error) {
      console.error('Failed to get LLM outfit advice:', error);
      throw new Error(`LLM问答失败: ${error}`);
    }
  }

  /**
   * 获取搜索建议
   */
  static async getSearchSuggestions(query: string): Promise<string[]> {
    try {
      const suggestions = await invoke<string[]>('get_outfit_search_suggestions', { query });
      return suggestions;
    } catch (error) {
      console.error('Failed to get search suggestions:', error);
      return [];
    }
  }

  /**
   * 基于分析结果生成搜索配置
   */
  static async generateSearchConfigFromAnalysis(
    analysisResult: any
  ): Promise<SearchConfig> {
    try {
      const config = await invoke<SearchConfig>('generate_search_config_from_analysis', {
        analysisResult,
      });
      return config;
    } catch (error) {
      console.error('Failed to generate search config from analysis:', error);
      throw new Error(`生成搜索配置失败: ${error}`);
    }
  }

  /**
   * 验证图像文件
   */
  static async validateOutfitImage(imagePath: string): Promise<boolean> {
    try {
      const isValid = await invoke<boolean>('validate_outfit_image', { imagePath });
      return isValid;
    } catch (error) {
      console.error('Failed to validate outfit image:', error);
      return false;
    }
  }

  /**
   * 获取支持的图像格式
   */
  static async getSupportedImageFormats(): Promise<string[]> {
    try {
      const formats = await invoke<string[]>('get_supported_image_formats');
      return formats;
    } catch (error) {
      console.error('Failed to get supported image formats:', error);
      return ['jpg', 'jpeg', 'png', 'webp'];
    }
  }

  /**
   * 获取默认搜索配置
   */
  static async getDefaultSearchConfig(): Promise<SearchConfig> {
    try {
      const config = await invoke<SearchConfig>('get_default_search_config');
      return config;
    } catch (error) {
      console.error('Failed to get default search config:', error);
      throw new Error(`获取默认配置失败: ${error}`);
    }
  }

  /**
   * 获取全局配置信息
   */
  static async getOutfitSearchConfig(): Promise<OutfitSearchConfigInfo> {
    try {
      const config = await invoke<OutfitSearchConfigInfo>('get_outfit_search_config');
      return config;
    } catch (error) {
      console.error('Failed to get outfit search config:', error);
      throw new Error(`获取配置信息失败: ${error}`);
    }
  }

  /**
   * 执行快速搜索（使用默认配置）
   */
  static async quickSearch(query: string, pageSize: number = 9): Promise<SearchResponse> {
    try {
      const defaultConfig = await this.getDefaultSearchConfig();
      const request: SearchRequest = {
        query,
        config: defaultConfig,
        page_size: pageSize,
        page_offset: 0,
      };
      return await this.searchSimilarOutfits(request);
    } catch (error) {
      console.error('Failed to perform quick search:', error);
      throw new Error(`快速搜索失败: ${error}`);
    }
  }

  /**
   * 执行分页搜索
   */
  static async searchWithPagination(
    request: SearchRequest,
    page: number,
    pageSize: number = 9
  ): Promise<SearchResponse> {
    try {
      const paginatedRequest: SearchRequest = {
        ...request,
        page_size: pageSize,
        page_offset: (page - 1) * pageSize,
      };
      return await this.searchSimilarOutfits(paginatedRequest);
    } catch (error) {
      console.error('Failed to perform paginated search:', error);
      throw new Error(`分页搜索失败: ${error}`);
    }
  }

  /**
   * 批量验证图像文件
   */
  static async validateMultipleImages(imagePaths: string[]): Promise<boolean[]> {
    try {
      const validationPromises = imagePaths.map(path => this.validateOutfitImage(path));
      const results = await Promise.all(validationPromises);
      return results;
    } catch (error) {
      console.error('Failed to validate multiple images:', error);
      return imagePaths.map(() => false);
    }
  }

  /**
   * 获取搜索统计信息
   */
  static async getSearchStats(response: SearchResponse): Promise<{
    totalResults: number;
    searchTime: number;
    averageScore: number;
    topCategories: string[];
  }> {
    const totalResults = response.total_size;
    const searchTime = response.search_time_ms;
    
    // 计算平均评分
    const averageScore = response.results.length > 0
      ? response.results.reduce((sum, result) => sum + result.relevance_score, 0) / response.results.length
      : 0;
    
    // 统计热门类别
    const categoryCount: Record<string, number> = {};
    response.results.forEach(result => {
      result.products.forEach(product => {
        categoryCount[product.category] = (categoryCount[product.category] || 0) + 1;
      });
    });
    
    const topCategories = Object.entries(categoryCount)
      .sort(([, a], [, b]) => b - a)
      .slice(0, 5)
      .map(([category]) => category);
    
    return {
      totalResults,
      searchTime,
      averageScore,
      topCategories,
    };
  }

  /**
   * 格式化搜索时间
   */
  static formatSearchTime(timeMs: number): string {
    if (timeMs < 1000) {
      return `${timeMs}ms`;
    } else if (timeMs < 60000) {
      return `${(timeMs / 1000).toFixed(1)}s`;
    } else {
      return `${Math.floor(timeMs / 60000)}m ${Math.floor((timeMs % 60000) / 1000)}s`;
    }
  }

  /**
   * 格式化相关性评分
   */
  static formatRelevanceScore(score: number): string {
    return `${(score * 100).toFixed(1)}%`;
  }

  /**
   * 检查是否有更多结果
   */
  static hasMoreResults(response: SearchResponse, currentPage: number, pageSize: number): boolean {
    const currentOffset = (currentPage - 1) * pageSize;
    return currentOffset + response.results.length < response.total_size;
  }

  /**
   * 计算总页数
   */
  static getTotalPages(totalSize: number, pageSize: number): number {
    return Math.ceil(totalSize / pageSize);
  }

  /**
   * 生成搜索摘要
   */
  static generateSearchSummary(response: SearchResponse, query: string): string {
    const { total_size, search_time_ms, results } = response;
    const timeStr = this.formatSearchTime(search_time_ms);
    
    if (total_size === 0) {
      return `未找到与"${query}"相关的结果`;
    }
    
    const avgScore = results.length > 0
      ? results.reduce((sum, r) => sum + r.relevance_score, 0) / results.length
      : 0;
    
    return `找到 ${total_size} 个相关结果，用时 ${timeStr}，平均相关度 ${this.formatRelevanceScore(avgScore)}`;
  }
}

/**
 * 导出默认实例
 */
export default OutfitSearchService;
