/**
 * 穿搭方案推荐服务
 * 遵循 Tauri 开发规范的服务层设计
 */

import { invoke } from '@tauri-apps/api/core';
import {
  OutfitRecommendationRequest,
  OutfitRecommendationResponse,
  OutfitRecommendation,
  SceneSearchRequest,
  DEFAULT_OUTFIT_RECOMMENDATION_REQUEST,
} from '../types/outfitRecommendation';

export class OutfitRecommendationService {
  /**
   * 生成穿搭方案推荐
   */
  static async generateRecommendations(
    request: Partial<OutfitRecommendationRequest>
  ): Promise<OutfitRecommendationResponse> {
    try {
      const fullRequest: OutfitRecommendationRequest = {
        ...DEFAULT_OUTFIT_RECOMMENDATION_REQUEST,
        ...request,
      } as OutfitRecommendationRequest;

      console.log('🎨 发送穿搭方案生成请求:', fullRequest);

      const response = await invoke<OutfitRecommendationResponse>(
        'generate_outfit_recommendations',
        { request: fullRequest }
      );

      console.log('✅ 穿搭方案生成成功:', response);
      return response;
    } catch (error) {
      console.error('❌ 穿搭方案生成失败:', error);
      throw new Error(`穿搭方案生成失败: ${error}`);
    }
  }

  /**
   * 基于查询快速生成推荐
   */
  static async quickGenerate(
    query: string,
    count: number = 3
  ): Promise<OutfitRecommendationResponse> {
    return this.generateRecommendations({
      query,
      count,
    });
  }

  /**
   * 基于风格生成推荐
   */
  static async generateByStyle(
    query: string,
    targetStyle: string,
    count: number = 3
  ): Promise<OutfitRecommendationResponse> {
    return this.generateRecommendations({
      query,
      target_style: targetStyle,
      count,
    });
  }

  /**
   * 基于场合生成推荐
   */
  static async generateByOccasion(
    query: string,
    occasions: string[],
    count: number = 3
  ): Promise<OutfitRecommendationResponse> {
    return this.generateRecommendations({
      query,
      occasions,
      count,
    });
  }

  /**
   * 基于季节生成推荐
   */
  static async generateBySeason(
    query: string,
    season: string,
    count: number = 3
  ): Promise<OutfitRecommendationResponse> {
    return this.generateRecommendations({
      query,
      season,
      count,
    });
  }

  /**
   * 基于色彩偏好生成推荐
   */
  static async generateByColors(
    query: string,
    colorPreferences: string[],
    count: number = 3
  ): Promise<OutfitRecommendationResponse> {
    return this.generateRecommendations({
      query,
      color_preferences: colorPreferences,
      count,
    });
  }

  /**
   * 生成场景检索请求
   * 用于将穿搭方案转换为场景检索参数
   */
  static generateSceneSearchRequest(
    recommendation: OutfitRecommendation,
    searchParams?: Partial<SceneSearchRequest['search_params']>
  ): SceneSearchRequest {
    // 生成场景描述
    const sceneDescription = this.generateSceneDescription(recommendation);

    // 获取所有风格标签
    const styleTags = this.getAllStyleTags(recommendation);

    return {
      outfit_id: recommendation.id,
      scene_description: sceneDescription,
      style_tags: styleTags,
      colors: recommendation.primary_colors,
      search_params: {
        scene_types: recommendation.scene_recommendations.map(s => s.scene_type),
        time_filters: recommendation.scene_recommendations.flatMap(s => s.time_of_day),
        lighting_filters: recommendation.scene_recommendations.map(s => s.lighting),
        limit: 20,
        ...searchParams,
      },
    };
  }

  /**
   * 生成场景描述
   */
  private static generateSceneDescription(recommendation: OutfitRecommendation): string {
    let description = `${recommendation.title} - ${recommendation.description}`;
    
    if (recommendation.style_tags.length > 0) {
      description += ` 风格: ${recommendation.style_tags.join(', ')}`;
    }
    
    if (recommendation.primary_colors.length > 0) {
      const colorNames = recommendation.primary_colors.map(c => c.name);
      description += ` 主要色彩: ${colorNames.join(', ')}`;
    }

    if (recommendation.occasions.length > 0) {
      description += ` 适合场合: ${recommendation.occasions.join(', ')}`;
    }
    
    return description;
  }

  /**
   * 获取所有风格标签
   */
  private static getAllStyleTags(recommendation: OutfitRecommendation): string[] {
    const allTags = [...recommendation.style_tags];
    
    // 添加整体风格
    if (recommendation.overall_style) {
      allTags.push(recommendation.overall_style);
    }
    
    // 添加单品风格标签
    recommendation.items.forEach(item => {
      allTags.push(...item.style_tags);
    });
    
    // 去重并排序
    return [...new Set(allTags)].sort();
  }

  /**
   * 格式化色彩信息
   */
  static formatColorInfo(color: { name: string; hex: string }): string {
    return `${color.name} (${color.hex})`;
  }

  /**
   * 检查方案是否适合指定季节
   */
  static isSeasonAppropriate(recommendation: OutfitRecommendation, season: string): boolean {
    return recommendation.seasons.includes(season);
  }

  /**
   * 检查方案是否适合指定场合
   */
  static isOccasionAppropriate(recommendation: OutfitRecommendation, occasion: string): boolean {
    return recommendation.occasions.includes(occasion);
  }

  /**
   * 获取推荐的主要色彩名称
   */
  static getPrimaryColorNames(recommendation: OutfitRecommendation): string[] {
    return recommendation.primary_colors.map(color => color.name);
  }

  /**
   * 获取推荐的TikTok优化建议摘要
   */
  static getTikTokTipsSummary(recommendation: OutfitRecommendation): string {
    if (recommendation.tiktok_tips.length === 0) {
      return '暂无TikTok优化建议';
    }
    
    if (recommendation.tiktok_tips.length === 1) {
      return recommendation.tiktok_tips[0];
    }
    
    return `${recommendation.tiktok_tips[0]}等${recommendation.tiktok_tips.length}条建议`;
  }

  /**
   * 获取推荐的场景类型摘要
   */
  static getSceneTypesSummary(recommendation: OutfitRecommendation): string {
    if (recommendation.scene_recommendations.length === 0) {
      return '暂无场景推荐';
    }
    
    const sceneTypes = [...new Set(recommendation.scene_recommendations.map(s => s.scene_type))];
    return sceneTypes.join('、');
  }

  /**
   * 验证推荐数据的完整性
   */
  static validateRecommendation(recommendation: OutfitRecommendation): {
    isValid: boolean;
    errors: string[];
  } {
    const errors: string[] = [];

    if (!recommendation.id) {
      errors.push('缺少方案ID');
    }

    if (!recommendation.title) {
      errors.push('缺少方案标题');
    }

    if (!recommendation.description) {
      errors.push('缺少方案描述');
    }

    if (recommendation.items.length === 0) {
      errors.push('缺少穿搭单品');
    }

    if (recommendation.primary_colors.length === 0) {
      errors.push('缺少主要色彩信息');
    }

    return {
      isValid: errors.length === 0,
      errors,
    };
  }
}

export default OutfitRecommendationService;
