use tauri::{command, State};
use crate::infrastructure::gemini_service::{GeminiService, GeminiConfig, RagGroundingRequest, RagGroundingResponse};
use crate::app_state::AppState;

/// RAG Grounding 查询命令
/// 基于数据存储的检索增强生成，参考 RAGUtils.py 中的 query_llm_with_grounding 实现
/// 现已支持多轮对话功能
#[command]
pub async fn query_rag_grounding(
    state: State<'_, AppState>,
    request: RagGroundingRequest,
) -> Result<RagGroundingResponse, String> {
    println!("🔍 收到RAG Grounding查询请求: {}", request.user_input);

    // 创建Gemini服务实例
    let config = GeminiConfig::default();
    let mut gemini_service = GeminiService::new(Some(config))
        .map_err(|e| format!("创建GeminiService失败: {}", e))?;

    // 如果请求包含会话管理参数，获取会话仓库
    let conversation_repo = if request.session_id.is_some() || request.include_history.unwrap_or(false) {
        match state.inner().get_conversation_repository() {
            Ok(repo) => Some(repo),
            Err(e) => {
                println!("⚠️ 获取会话仓库失败，将使用单轮对话模式: {}", e);
                None
            }
        }
    } else {
        None
    };

    // 执行RAG Grounding查询
    let response = if conversation_repo.is_some() {
        gemini_service
            .query_llm_with_grounding_multi_turn(request, conversation_repo)
            .await
            .map_err(|e| {
                eprintln!("多轮RAG Grounding查询失败: {}", e);
                format!("多轮RAG Grounding查询失败: {}", e)
            })?
    } else {
        gemini_service
            .query_llm_with_grounding(request)
            .await
            .map_err(|e| {
                eprintln!("RAG Grounding查询失败: {}", e);
                format!("RAG Grounding查询失败: {}", e)
            })?
    };

    println!("✅ RAG Grounding查询成功，响应时间: {}ms", response.response_time_ms);

    Ok(response)
}

/// 测试RAG Grounding连接
#[command]
pub async fn test_rag_grounding_connection(
    _state: State<'_, AppState>,
) -> Result<String, String> {
    println!("🔧 测试RAG Grounding连接");

    // 创建Gemini服务实例
    let config = GeminiConfig::default();
    let mut gemini_service = GeminiService::new(Some(config))
        .map_err(|e| format!("创建GeminiService失败: {}", e))?;

    // 创建测试请求
    let test_request = RagGroundingRequest {
        user_input: "测试连接".to_string(),
        config: None,
        session_id: Some("test-session".to_string()),
        include_history: Some(false),
        max_history_messages: None,
        system_prompt: None,
    };

    // 执行测试查询
    match gemini_service.query_llm_with_grounding(test_request).await {
        Ok(response) => {
            println!("✅ RAG Grounding连接测试成功");
            Ok(format!("连接测试成功，响应时间: {}ms", response.response_time_ms))
        }
        Err(e) => {
            eprintln!("❌ RAG Grounding连接测试失败: {}", e);
            Err(format!("连接测试失败: {}", e))
        }
    }
}

/// 获取RAG Grounding配置信息
#[command]
pub async fn get_rag_grounding_config(
    _state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
    println!("📋 获取RAG Grounding配置信息");

    let config = GeminiConfig::default();
    
    let config_info = serde_json::json!({
        "base_url": config.base_url,
        "model_name": config.model_name,
        "timeout": config.timeout,
        "max_retries": config.max_retries,
        "retry_delay": config.retry_delay,
        "temperature": config.temperature,
        "max_tokens": config.max_tokens,
        "cloudflare_project_id": config.cloudflare_project_id,
        "cloudflare_gateway_id": config.cloudflare_gateway_id,
        "google_project_id": config.google_project_id,
        "regions": config.regions
    });

    Ok(config_info)
}

#[cfg(test)]
mod tests {

    use crate::infrastructure::gemini_service::RagGroundingConfig;

    #[test]
    fn test_rag_grounding_config_default() {
        let config = RagGroundingConfig::default();
        
        assert_eq!(config.project_id, "gen-lang-client-0413414134");
        assert_eq!(config.location, "global");
        assert_eq!(config.model_id, "gemini-2.5-flash");
        assert_eq!(config.temperature, 1.0);
        assert_eq!(config.max_output_tokens, 8192);
    }
}
