use anyhow::Result;
use std::sync::Arc;

use crate::data::repositories::conversation_repository::ConversationRepository;
use crate::data::models::conversation::{
    ConversationSession, ConversationMessage, ConversationHistory,
    CreateConversationSessionRequest, AddMessageRequest, ConversationHistoryQuery,
    MultiTurnConversationRequest, MultiTurnConversationResponse,
    MessageRole, MessageContent, ConversationStats,
};
use crate::infrastructure::gemini_service::{GeminiService, GeminiConfig};

/// 会话管理业务服务
/// 遵循 Tauri 开发规范的业务逻辑层设计模式
pub struct ConversationService {
    repository: Arc<ConversationRepository>,
}

impl ConversationService {
    /// 创建新的会话服务实例
    pub fn new(repository: Arc<ConversationRepository>) -> Self {
        Self { repository }
    }

    /// 创建新会话
    pub async fn create_session(&self, request: CreateConversationSessionRequest) -> Result<ConversationSession> {
        self.repository.create_session(request)
    }

    /// 获取会话信息
    pub async fn get_session(&self, session_id: &str) -> Result<Option<ConversationSession>> {
        self.repository.get_session(session_id)
    }

    /// 获取会话历史
    pub async fn get_conversation_history(&self, query: ConversationHistoryQuery) -> Result<ConversationHistory> {
        self.repository.get_conversation_history(query)
    }

    /// 获取会话列表
    pub async fn get_sessions(&self, limit: Option<u32>, offset: Option<u32>) -> Result<Vec<ConversationSession>> {
        self.repository.get_sessions(limit, offset)
    }

    /// 删除会话
    pub async fn delete_session(&self, session_id: &str) -> Result<()> {
        self.repository.delete_session(session_id)
    }

    /// 添加消息到会话
    pub async fn add_message(&self, request: AddMessageRequest) -> Result<ConversationMessage> {
        self.repository.add_message(request)
    }

    /// 多轮对话处理
    pub async fn process_multi_turn_conversation(
        &self,
        request: MultiTurnConversationRequest,
    ) -> Result<MultiTurnConversationResponse> {
        let start_time = std::time::Instant::now();

        // 1. 确定或创建会话
        let session_id = match request.session_id {
            Some(id) => {
                // 验证会话是否存在
                if self.repository.get_session(&id)?.is_none() {
                    return Err(anyhow::anyhow!("Session not found: {}", id));
                }
                id
            }
            None => {
                // 创建新会话
                let session = self.repository.create_session(CreateConversationSessionRequest {
                    title: Some("新对话".to_string()),
                    metadata: None,
                })?;
                session.id
            }
        };

        // 2. 添加用户消息到会话历史
        let user_message = self.repository.add_message(AddMessageRequest {
            session_id: session_id.clone(),
            role: MessageRole::User,
            content: vec![MessageContent::Text { text: request.user_message.clone() }],
            metadata: None,
        })?;

        // 3. 获取历史消息（如果需要）
        let history_messages = if request.include_history.unwrap_or(true) {
            let max_messages = request.max_history_messages.unwrap_or(1);
            let history = self.repository.get_conversation_history(ConversationHistoryQuery {
                session_id: session_id.clone(),
                limit: Some(max_messages),
                offset: None,
                include_system_messages: Some(false),
            })?;
            
            // 排除刚刚添加的用户消息，因为它会在API调用中单独处理
            history.messages.into_iter()
                .filter(|msg| msg.id != user_message.id)
                .collect()
        } else {
            Vec::new()
        };

        // 4. 调用Gemini API进行多轮对话
        let mut gemini_service = GeminiService::new(Some(GeminiConfig::default()))?;
        let assistant_response = self.call_gemini_with_history(
            &mut gemini_service,
            &request.user_message,
            &history_messages,
            request.system_prompt.as_deref(),
        ).await?;

        // 5. 添加助手回复到会话历史
        let assistant_message = self.repository.add_message(AddMessageRequest {
            session_id: session_id.clone(),
            role: MessageRole::Assistant,
            content: vec![MessageContent::Text { text: assistant_response.clone() }],
            metadata: request.config.clone(),
        })?;

        let elapsed = start_time.elapsed();

        Ok(MultiTurnConversationResponse {
            session_id,
            assistant_message: assistant_response,
            message_id: assistant_message.id,
            response_time_ms: elapsed.as_millis() as u64,
            model_used: "gemini-2.5-flash".to_string(),
            metadata: None,
        })
    }

    /// 调用Gemini API进行多轮对话
    async fn call_gemini_with_history(
        &self,
        gemini_service: &mut GeminiService,
        current_message: &str,
        history_messages: &[ConversationMessage],
        _system_prompt: Option<&str>,
    ) -> Result<String> {
        use crate::infrastructure::gemini_service::{GenerateContentRequest, ContentPart, Part, GenerationConfig};

        // 构建contents数组，包含历史消息
        let mut contents = Vec::new();

        // 添加历史消息
        for msg in history_messages {
            let parts = self.convert_message_content_to_parts(&msg.content)?;
            contents.push(ContentPart {
                role: msg.role.to_string(),
                parts,
            });
        }

        // 添加当前用户消息
        contents.push(ContentPart {
            role: "user".to_string(),
            parts: vec![Part::Text { text: current_message.to_string() }],
        });

        // 构建请求
        let request = GenerateContentRequest {
            contents,
            generation_config: GenerationConfig {
                temperature: 0.7,
                top_k: 32,
                top_p: 1.0,
                max_output_tokens: 4096,
            },
        };

        // 调用Gemini API
        gemini_service.generate_content_with_request(request).await
    }

    /// 将消息内容转换为Gemini API的Part格式
    fn convert_message_content_to_parts(&self, content: &[MessageContent]) -> Result<Vec<crate::infrastructure::gemini_service::Part>> {
        use crate::infrastructure::gemini_service::{Part, FileData, InlineData};

        let mut parts = Vec::new();
        for item in content {
            match item {
                MessageContent::Text { text } => {
                    parts.push(Part::Text { text: text.clone() });
                }
                MessageContent::File { file_uri, mime_type, .. } => {
                    parts.push(Part::FileData {
                        file_data: FileData {
                            mime_type: mime_type.clone(),
                            file_uri: file_uri.clone(),
                        }
                    });
                }
                MessageContent::InlineData { data, mime_type, .. } => {
                    parts.push(Part::InlineData {
                        inline_data: InlineData {
                            mime_type: mime_type.clone(),
                            data: data.clone(),
                        }
                    });
                }
            }
        }
        Ok(parts)
    }

    /// 获取会话统计信息
    pub async fn get_conversation_stats(&self) -> Result<ConversationStats> {
        self.repository.get_conversation_stats()
    }

    /// 清理过期会话
    pub async fn cleanup_expired_sessions(&self, max_inactive_days: u32) -> Result<u32> {
        self.repository.cleanup_expired_sessions(max_inactive_days)
    }

    /// 更新会话标题
    pub async fn update_session_title(&self, session_id: &str, title: Option<String>) -> Result<()> {
        // 获取会话
        let mut session = self.repository.get_session(session_id)?
            .ok_or_else(|| anyhow::anyhow!("Session not found: {}", session_id))?;

        // 更新标题
        session.update_title(title);

        // 这里需要在repository中添加update_session方法
        // 暂时通过重新创建来模拟更新
        Ok(())
    }

    /// 获取最近的对话摘要（用于生成会话标题）
    pub async fn generate_session_summary(&self, session_id: &str) -> Result<String> {
        let history = self.repository.get_conversation_history(ConversationHistoryQuery {
            session_id: session_id.to_string(),
            limit: Some(10), // 获取最近10条消息
            offset: None,
            include_system_messages: Some(false),
        })?;

        if history.messages.is_empty() {
            return Ok("新对话".to_string());
        }

        // 提取第一条用户消息作为摘要
        for message in &history.messages {
            if message.role == MessageRole::User {
                for content in &message.content {
                    if let MessageContent::Text { text } = content {
                        // 截取前50个字符作为标题
                        let summary = if text.len() > 50 {
                            format!("{}...", &text[..47])
                        } else {
                            text.clone()
                        };
                        return Ok(summary);
                    }
                }
            }
        }

        Ok("新对话".to_string())
    }
}


