use tauri::State;
use anyhow::Result;

use crate::app_state::AppState;
use crate::data::models::gemini_analysis::{AnalyzeImageRequest, AnalyzeImageResponse};
use crate::data::models::outfit_search::{
    SearchRequest, SearchResponse, LLMQueryRequest, LLMQueryResponse,
    OutfitSearchGlobalConfig
};
use crate::infrastructure::gemini_service::{GeminiService, GeminiConfig};

/// 分析服装图像
/// 遵循 Tauri 开发规范的命令接口设计原则
#[tauri::command]
pub async fn analyze_outfit_image(
    _state: State<'_, AppState>,
    request: AnalyzeImageRequest,
) -> Result<AnalyzeImageResponse, String> {
    // 创建Gemini服务
    let config = GeminiConfig::default();
    let mut gemini_service = GeminiService::new(Some(config))
        .map_err(|e| format!("Failed to create GeminiService: {}", e))?;

    // 执行图像分析
    let analysis_result = gemini_service
        .analyze_outfit_image(&request.image_path)
        .await
        .map_err(|e| {
            eprintln!("Failed to analyze outfit image: {}", e);
            format!("图像分析失败: {}", e)
        })?;

    // 解析JSON结果
    let parsed_result: serde_json::Value = serde_json::from_str(&analysis_result)
        .map_err(|e| format!("Failed to parse analysis result: {}", e))?;

    // 构建响应
    Ok(AnalyzeImageResponse {
        result: parsed_result,
        analysis_time_ms: 1500, // 这里应该记录实际的分析时间
        analyzed_at: chrono::Utc::now(),
    })
}

/// 搜索相似服装
#[tauri::command]
pub async fn search_similar_outfits(
    _state: State<'_, AppState>,
    _request: SearchRequest,
) -> Result<SearchResponse, String> {
    // TODO: 实现真实的搜索逻辑

    // 执行搜索（暂时返回模拟数据）
    // TODO: 实现真实的搜索逻辑
    Ok(SearchResponse {
        results: vec![],
        total_size: 0,
        next_page_token: None,
        search_time_ms: 100,
        searched_at: chrono::Utc::now(),
    })
}

/// LLM问答
#[tauri::command]
pub async fn ask_llm_outfit_advice(
    _state: State<'_, AppState>,
    request: LLMQueryRequest,
) -> Result<LLMQueryResponse, String> {
    // 创建Gemini服务
    let config = GeminiConfig::default();
    let mut gemini_service = GeminiService::new(Some(config))
        .map_err(|e| format!("Failed to create GeminiService: {}", e))?;

    // 执行LLM问答
    let answer = gemini_service
        .ask_outfit_advice(&request.user_input)
        .await
        .map_err(|e| {
            eprintln!("Failed to get LLM outfit advice: {}", e);
            format!("LLM问答失败: {}", e)
        })?;

    // 构建响应
    Ok(LLMQueryResponse {
        answer,
        related_results: vec![], // 暂时返回空的相关结果
        response_time_ms: 1000,
        responded_at: chrono::Utc::now(),
    })
}

/// 获取搜索建议
#[tauri::command]
pub async fn get_outfit_search_suggestions(
    _state: State<'_, AppState>,
    query: String,
) -> Result<Vec<String>, String> {
    // 基于查询生成搜索建议
    let suggestions = generate_search_suggestions(&query);
    Ok(suggestions)
}

/// 基于分析结果生成搜索配置
#[tauri::command]
pub async fn generate_search_config_from_analysis(
    _state: State<'_, AppState>,
    _analysis_result: crate::data::models::gemini_analysis::OutfitAnalysisResult,
) -> Result<crate::data::models::outfit_search::SearchConfig, String> {
    // TODO: 实现基于分析结果生成搜索配置的逻辑
    // 暂时返回默认配置
    use crate::data::models::outfit_search::{SearchConfig, RelevanceThreshold};
    use std::collections::HashMap;

    Ok(SearchConfig {
        relevance_threshold: RelevanceThreshold::High,
        categories: vec![],
        environments: vec![],
        color_filters: HashMap::new(),
        design_styles: HashMap::new(),
        max_keywords: 10,
    })
}

/// 验证图像文件
#[tauri::command]
pub async fn validate_outfit_image(
    _state: State<'_, AppState>,
    image_path: String,
) -> Result<bool, String> {
    // 检查文件是否存在
    if !std::path::Path::new(&image_path).exists() {
        return Ok(false);
    }
    
    // 检查文件扩展名
    let valid_extensions = ["jpg", "jpeg", "png", "webp"];
    let extension = std::path::Path::new(&image_path)
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.to_lowercase());
    
    match extension {
        Some(ext) if valid_extensions.contains(&ext.as_str()) => Ok(true),
        _ => Ok(false),
    }
}

/// 获取支持的图像格式
#[tauri::command]
pub async fn get_supported_image_formats(
    _state: State<'_, AppState>,
) -> Result<Vec<String>, String> {
    Ok(vec![
        "jpg".to_string(),
        "jpeg".to_string(),
        "png".to_string(),
        "webp".to_string(),
    ])
}

/// 获取默认搜索配置
#[tauri::command]
pub async fn get_default_search_config(
    _state: State<'_, AppState>,
) -> Result<crate::data::models::outfit_search::SearchConfig, String> {
    Ok(crate::data::models::outfit_search::SearchConfig::default())
}

/// 获取全局配置信息
#[tauri::command]
pub async fn get_outfit_search_config(
    _state: State<'_, AppState>,
) -> Result<OutfitSearchConfigInfo, String> {
    let config = OutfitSearchGlobalConfig::default();
    Ok(OutfitSearchConfigInfo {
        google_project_id: config.google_project_id,
        vertex_ai_app_id: config.vertex_ai_app_id,
        storage_bucket_name: config.storage_bucket_name,
        data_store_id: config.data_store_id,
    })
}

/// 配置信息（用于前端显示，不包含敏感信息）
#[derive(serde::Serialize)]
pub struct OutfitSearchConfigInfo {
    pub google_project_id: String,
    pub vertex_ai_app_id: String,
    pub storage_bucket_name: String,
    pub data_store_id: String,
}



/// 生成搜索建议的辅助函数
fn generate_search_suggestions(query: &str) -> Vec<String> {
    let base_suggestions = vec![
        "休闲搭配".to_string(),
        "正式搭配".to_string(),
        "运动风格".to_string(),
        "街头风格".to_string(),
        "简约风格".to_string(),
        "复古风格".to_string(),
        "牛仔裤搭配".to_string(),
        "连衣裙搭配".to_string(),
        "外套搭配".to_string(),
        "夏季搭配".to_string(),
        "冬季搭配".to_string(),
        "约会搭配".to_string(),
        "工作搭配".to_string(),
        "聚会搭配".to_string(),
    ];
    
    if query.is_empty() {
        return base_suggestions;
    }
    
    // 基于查询过滤和排序建议
    let mut filtered_suggestions: Vec<String> = base_suggestions
        .into_iter()
        .filter(|suggestion| {
            suggestion.contains(query) || 
            query.chars().any(|c| suggestion.contains(c))
        })
        .collect();
    
    // 如果过滤后的建议太少，添加一些通用建议
    if filtered_suggestions.len() < 5 {
        filtered_suggestions.extend(vec![
            format!("{} 搭配", query),
            format!("{} 风格", query),
            format!("如何搭配 {}", query),
        ]);
    }
    
    // 限制建议数量
    filtered_suggestions.truncate(10);
    filtered_suggestions
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_search_suggestions() {
        let suggestions = generate_search_suggestions("牛仔");
        assert!(suggestions.iter().any(|s| s.contains("牛仔")));
        assert!(suggestions.len() <= 10);
    }

    #[test]
    fn test_generate_search_suggestions_empty() {
        let suggestions = generate_search_suggestions("");
        assert!(!suggestions.is_empty());
        assert!(suggestions.len() <= 10);
    }

    #[test]
    fn test_outfit_search_config_info_serialization() {
        let config_info = OutfitSearchConfigInfo {
            google_project_id: "test-project".to_string(),
            vertex_ai_app_id: "test-app".to_string(),
            storage_bucket_name: "test-bucket".to_string(),
            data_store_id: "test-store".to_string(),
        };
        
        let serialized = serde_json::to_string(&config_info).unwrap();
        assert!(serialized.contains("test-project"));
    }
}

/// 获取所有服装搜索相关的Tauri命令名称
pub fn get_outfit_search_command_names() -> Vec<&'static str> {
    vec![
        "analyze_outfit_image",
        "search_similar_outfits",
        "ask_llm_outfit_advice",
        "get_outfit_search_suggestions",
        "generate_search_config_from_analysis",
        "validate_outfit_image",
        "get_supported_image_formats",
        "get_default_search_config",
        "get_outfit_search_config",
    ]
}
