use anyhow::Result;
use crate::data::models::outfit_recommendation::OutfitRecommendation;
use crate::data::models::material_search::{
    MaterialSearchRequest, MaterialSearchResponse, GenerateSearchQueryRequest,
    GenerateSearchQueryResponse, GenerateSearchQueryOptions,
};
use crate::infrastructure::gemini_service::{GeminiService, GeminiConfig};


/// 素材检索服务
pub struct MaterialSearchService {
    gemini_service: GeminiService,
}

impl MaterialSearchService {
    /// 创建新的素材检索服务实例
    pub fn new() -> Self {
        let config = GeminiConfig::default();
        let gemini_service = GeminiService::new(Some(config))
            .expect("Failed to create GeminiService");
        
        Self { gemini_service }
    }

    /// 为穿搭方案生成检索条件
    pub async fn generate_search_query(
        &self,
        recommendation: &OutfitRecommendation,
        options: Option<GenerateSearchQueryOptions>,
    ) -> Result<GenerateSearchQueryResponse> {
        let request = GenerateSearchQueryRequest {
            recommendation: recommendation.clone(),
            options,
        };

        // 调用现有的生成检索条件逻辑
        self.generate_search_query_internal(&request).await
    }

    /// 执行素材检索
    pub async fn search_materials(
        &self,
        request: &MaterialSearchRequest,
    ) -> Result<MaterialSearchResponse> {
        // 转换为标准搜索请求
        let search_request = crate::data::models::outfit_search::SearchRequest {
            query: request.query.clone(),
            config: request.search_config.clone().into(),
            page_size: request.pagination.page_size as usize,
            page_offset: ((request.pagination.page - 1) * request.pagination.page_size) as usize,
        };

        // 执行搜索
        let mut gemini_service = self.gemini_service.clone();
        let search_response = execute_material_search(&mut gemini_service, &search_request).await?;

        // 转换搜索结果
        let material_results: Vec<crate::data::models::material_search::MaterialSearchResult> = 
            search_response.results
                .into_iter()
                .map(|result| crate::data::models::material_search::MaterialSearchResult::from(result))
                .collect();

        Ok(MaterialSearchResponse {
            results: material_results,
            total_size: search_response.total_size as u32,
            current_page: request.pagination.page,
            page_size: request.pagination.page_size,
            total_pages: ((search_response.total_size as f64) / (request.pagination.page_size as f64)).ceil() as u32,
            search_time_ms: search_response.search_time_ms,
            searched_at: chrono::Utc::now(),
            next_page_token: search_response.next_page_token,
        })
    }

    /// 内部生成检索条件的实现
    async fn generate_search_query_internal(
        &self,
        request: &GenerateSearchQueryRequest,
    ) -> Result<GenerateSearchQueryResponse> {
        // 获取生成选项，使用默认值如果未提供
        let default_options = GenerateSearchQueryOptions::default();
        let options = request.options.as_ref().unwrap_or(&default_options);
        
        // 构建搜索查询字符串
        let mut query_parts = Vec::new();
        
        // 添加基础描述
        query_parts.push("model".to_string());
        query_parts.push("fashion".to_string());
        query_parts.push("outfit".to_string());
        
        // 添加整体风格
        if options.include_styles.unwrap_or(true) {
            query_parts.push(request.recommendation.overall_style.clone());
            
            // 添加风格标签
            for tag in &request.recommendation.style_tags {
                if !tag.is_empty() {
                    query_parts.push(tag.clone());
                }
            }
        }
        
        // 添加适合场合
        if options.include_occasions.unwrap_or(true) {
            for occasion in &request.recommendation.occasions {
                if !occasion.is_empty() {
                    query_parts.push(occasion.clone());
                }
            }
        }
        
        // 添加季节信息
        if options.include_seasons.unwrap_or(false) {
            for season in &request.recommendation.seasons {
                if !season.is_empty() {
                    query_parts.push(season.clone());
                }
            }
        }
        
        // 添加色彩信息
        if options.include_colors.unwrap_or(true) {
            query_parts.push(request.recommendation.color_theme.clone());
            
            // 添加主要色彩名称
            for color in &request.recommendation.primary_colors {
                if !color.name.is_empty() {
                    query_parts.push(color.name.clone());
                }
            }
        }
        
        // 构建最终查询字符串
        let query = query_parts.join(" ");
        
        // 创建搜索配置
        let search_config = crate::data::models::material_search::MaterialSearchConfig::default();
        
        println!("🔍 为方案 '{}' 生成检索条件: {}", request.recommendation.title, query);
        
        Ok(GenerateSearchQueryResponse {
            query,
            search_config,
            generation_time_ms: 50, // 简单估算
            generated_at: chrono::Utc::now(),
        })
    }
}

impl Clone for MaterialSearchService {
    fn clone(&self) -> Self {
        Self::new()
    }
}

/// 执行素材搜索的内部函数
async fn execute_material_search(
    gemini_service: &mut GeminiService,
    request: &crate::data::models::outfit_search::SearchRequest,
) -> Result<crate::data::models::outfit_search::SearchResponse> {
    // 直接使用outfit_search_commands中的vertex搜索服务
    use crate::presentation::commands::outfit_search_commands::execute_vertex_ai_search;

    println!("🔍 开始执行素材库搜索...");
    println!("搜索查询: {}", request.query);

    execute_vertex_ai_search(gemini_service, request).await
}
