use anyhow::Result;
use tauri::State;
use chrono::Utc;

use crate::app_state::AppState;
use crate::data::models::material_search::{
    MaterialSearchRequest, MaterialSearchResponse, MaterialSearchResult,
    GenerateSearchQueryRequest, GenerateSearchQueryResponse,
    MaterialSearchConfig, MaterialSearchPagination,
};
use crate::data::models::outfit_search::{SearchRequest, SearchResponse};
use crate::infrastructure::gemini_service::{GeminiConfig, GeminiService};

/// 为穿搭方案生成智能检索条件
#[tauri::command]
pub async fn generate_material_search_query(
    _state: State<'_, AppState>,
    request: GenerateSearchQueryRequest,
) -> Result<GenerateSearchQueryResponse, String> {
    let start_time = std::time::Instant::now();
    
    println!("🔍 开始为穿搭方案生成素材检索条件...");
    println!("方案标题: {}", request.recommendation.title);
    
    // 获取生成选项，使用默认值如果未提供
    let options = request.options.unwrap_or_default();
    
    // 构建搜索查询字符串
    let mut query_parts = Vec::new();
    
    // 添加基础描述
    query_parts.push("model".to_string());
    
    // 添加风格信息
    if options.include_styles.unwrap_or(true) {
        query_parts.push(request.recommendation.overall_style.clone());
        
        // 添加风格标签（限制数量）
        let style_tags: Vec<String> = request.recommendation.style_tags
            .iter()
            .take(3) // 限制最多3个标签
            .cloned()
            .collect();
        query_parts.extend(style_tags);
    }
    
    // 添加场合信息
    if options.include_occasions.unwrap_or(true) {
        let occasions: Vec<String> = request.recommendation.occasions
            .iter()
            .take(2) // 限制最多2个场合
            .cloned()
            .collect();
        query_parts.extend(occasions);
    }
    
    // 添加季节信息（如果启用）
    if options.include_seasons.unwrap_or(false) {
        let seasons: Vec<String> = request.recommendation.seasons
            .iter()
            .take(1) // 限制最多1个季节
            .cloned()
            .collect();
        query_parts.extend(seasons);
    }
    
    // 构建最终查询字符串
    let query = query_parts.join(" ");
    
    // 构建搜索配置
    let mut search_config = MaterialSearchConfig::default();
    
    // 设置类别过滤（基于穿搭单品）
    if !request.recommendation.items.is_empty() {
        search_config.categories = request.recommendation.items
            .iter()
            .map(|item| item.category.clone())
            .collect::<std::collections::HashSet<_>>() // 去重
            .into_iter()
            .collect();
    }
    
    // 设置环境标签（基于场景推荐）
    if !request.recommendation.scene_recommendations.is_empty() {
        search_config.environments = request.recommendation.scene_recommendations
            .iter()
            .map(|scene| scene.scene_type.clone())
            .collect::<std::collections::HashSet<_>>() // 去重
            .into_iter()
            .collect();
    }
    
    // 设置设计风格
    for item in &request.recommendation.items {
        if !item.style_tags.is_empty() {
            search_config.design_styles.insert(
                item.category.clone(),
                item.style_tags.clone(),
            );
        }
    }
    
    // 添加颜色过滤器（如果启用）
    if options.include_colors.unwrap_or(true) {
        use crate::data::models::material_search::MaterialColorFilter;

        for color_info in &request.recommendation.primary_colors {
            // 简单的颜色名称到HSV的映射（实际应用中可能需要更复杂的颜色解析）
            let hsv_color = parse_color_name_to_hsv(&color_info.name);
            
            let color_filter = MaterialColorFilter {
                enabled: true,
                color: hsv_color,
                hue_threshold: 0.1,
                saturation_threshold: 0.2,
                value_threshold: 0.3,
            };
            
            // 为主要类别添加颜色过滤器
            if let Some(main_category) = search_config.categories.first() {
                search_config.color_filters.insert(main_category.clone(), color_filter);
                break; // 只为第一个类别添加颜色过滤器
            }
        }
    }
    
    let generation_time_ms = start_time.elapsed().as_millis() as u64;
    
    println!("✅ 素材检索条件生成完成");
    println!("生成的查询: {}", query);
    println!("类别过滤: {:?}", search_config.categories);
    println!("环境标签: {:?}", search_config.environments);
    
    Ok(GenerateSearchQueryResponse {
        query,
        search_config,
        generation_time_ms,
        generated_at: Utc::now(),
    })
}

/// 执行素材库检索
#[tauri::command]
pub async fn search_materials_for_outfit(
    _state: State<'_, AppState>,
    request: MaterialSearchRequest,
) -> Result<MaterialSearchResponse, String> {
    let start_time = std::time::Instant::now();
    
    println!("🔍 开始执行素材库检索...");
    println!("查询: {}", request.query);
    println!("方案ID: {}", request.recommendation_id);
    println!("页码: {}, 每页: {}", request.pagination.page, request.pagination.page_size);
    
    // 创建Gemini服务实例用于获取访问令牌
    let config = GeminiConfig::default();
    let mut gemini_service = GeminiService::new(Some(config))
        .map_err(|e| format!("Failed to create GeminiService: {}", e))?;
    
    // 转换为标准搜索请求
    let search_request = 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,
    };
    
    // 执行搜索（复用现有的outfit search逻辑）
    let search_response = execute_material_search(&mut gemini_service, &search_request)
        .await
        .map_err(|e| {
            eprintln!("素材检索失败: {}", e);
            format!("素材检索失败: {}", e)
        })?;
    
    // 转换搜索结果
    let material_results: Vec<MaterialSearchResult> = search_response.results
        .into_iter()
        .map(MaterialSearchResult::from)
        .collect();
    
    // 计算分页信息
    let total_pages = if request.pagination.page_size > 0 {
        (search_response.total_size as u32 + request.pagination.page_size - 1) / request.pagination.page_size
    } else {
        1
    };
    
    let search_time_ms = start_time.elapsed().as_millis() as u64;
    
    println!("✅ 素材检索完成");
    println!("找到 {} 个结果，用时 {}ms", material_results.len(), search_time_ms);
    
    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_time_ms,
        searched_at: Utc::now(),
        next_page_token: search_response.next_page_token,
    })
}

/// 快速素材检索（使用默认配置）
#[tauri::command]
pub async fn quick_material_search(
    _state: State<'_, AppState>,
    recommendation_id: String,
    query: String,
    page: Option<u32>,
    page_size: Option<u32>,
) -> Result<MaterialSearchResponse, String> {
    let request = MaterialSearchRequest {
        query,
        recommendation_id,
        search_config: MaterialSearchConfig::default(),
        pagination: MaterialSearchPagination {
            page: page.unwrap_or(1),
            page_size: page_size.unwrap_or(9),
        },
    };
    
    search_materials_for_outfit(_state, request).await
}

/// 执行素材搜索的内部函数
async fn execute_material_search(
    gemini_service: &mut GeminiService,
    request: &SearchRequest,
) -> Result<SearchResponse, anyhow::Error> {
    // 直接使用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
}

/// 简单的颜色名称到HSV转换函数
/// 实际应用中应该使用更完善的颜色解析库
fn parse_color_name_to_hsv(color_name: &str) -> crate::data::models::material_search::MaterialColorHSV {
    use crate::data::models::material_search::MaterialColorHSV;
    
    match color_name.to_lowercase().as_str() {
        "红色" | "红" | "red" => MaterialColorHSV { hue: 0.0, saturation: 1.0, value: 1.0 },
        "橙色" | "橙" | "orange" => MaterialColorHSV { hue: 0.08, saturation: 1.0, value: 1.0 },
        "黄色" | "黄" | "yellow" => MaterialColorHSV { hue: 0.17, saturation: 1.0, value: 1.0 },
        "绿色" | "绿" | "green" => MaterialColorHSV { hue: 0.33, saturation: 1.0, value: 1.0 },
        "蓝色" | "蓝" | "blue" => MaterialColorHSV { hue: 0.67, saturation: 1.0, value: 1.0 },
        "紫色" | "紫" | "purple" => MaterialColorHSV { hue: 0.83, saturation: 1.0, value: 1.0 },
        "粉色" | "粉" | "pink" => MaterialColorHSV { hue: 0.92, saturation: 0.5, value: 1.0 },
        "白色" | "白" | "white" => MaterialColorHSV { hue: 0.0, saturation: 0.0, value: 1.0 },
        "黑色" | "黑" | "black" => MaterialColorHSV { hue: 0.0, saturation: 0.0, value: 0.0 },
        "灰色" | "灰" | "gray" | "grey" => MaterialColorHSV { hue: 0.0, saturation: 0.0, value: 0.5 },
        "棕色" | "棕" | "brown" => MaterialColorHSV { hue: 0.08, saturation: 0.8, value: 0.6 },
        _ => MaterialColorHSV { hue: 0.0, saturation: 0.5, value: 0.8 }, // 默认中性色
    }
}
