use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};

/// 会话消息类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum MessageRole {
    #[serde(rename = "user")]
    User,
    #[serde(rename = "assistant")]
    Assistant,
    #[serde(rename = "system")]
    System,
}

impl ToString for MessageRole {
    fn to_string(&self) -> String {
        match self {
            MessageRole::User => "user".to_string(),
            MessageRole::Assistant => "assistant".to_string(),
            MessageRole::System => "system".to_string(),
        }
    }
}

/// 消息内容类型
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum MessageContent {
    #[serde(rename = "text")]
    Text { text: String },
    #[serde(rename = "file")]
    File { 
        file_uri: String, 
        mime_type: String,
        description: Option<String>,
    },
    #[serde(rename = "inline_data")]
    InlineData { 
        data: String, 
        mime_type: String,
        description: Option<String>,
    },
}

/// 会话消息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationMessage {
    pub id: String,
    pub session_id: String,
    pub role: MessageRole,
    pub content: Vec<MessageContent>,
    pub timestamp: DateTime<Utc>,
    pub metadata: Option<serde_json::Value>,
}

/// 会话会话
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationSession {
    pub id: String,
    pub title: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub is_active: bool,
    pub metadata: Option<serde_json::Value>,
}

/// 创建会话请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateConversationSessionRequest {
    pub title: Option<String>,
    pub metadata: Option<serde_json::Value>,
}

/// 添加消息请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddMessageRequest {
    pub session_id: String,
    pub role: MessageRole,
    pub content: Vec<MessageContent>,
    pub metadata: Option<serde_json::Value>,
}

/// 会话历史查询参数
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationHistoryQuery {
    pub session_id: String,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
    pub include_system_messages: Option<bool>,
}

/// 会话历史响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationHistory {
    pub session: ConversationSession,
    pub messages: Vec<ConversationMessage>,
    pub total_count: u32,
}

/// 多轮对话请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiTurnConversationRequest {
    pub session_id: Option<String>,
    pub user_message: String,
    pub include_history: Option<bool>,
    pub max_history_messages: Option<u32>,
    pub system_prompt: Option<String>,
    pub config: Option<serde_json::Value>,
}

/// 多轮对话响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiTurnConversationResponse {
    pub session_id: String,
    pub assistant_message: String,
    pub message_id: String,
    pub response_time_ms: u64,
    pub model_used: String,
    pub metadata: Option<serde_json::Value>,
}

impl ConversationMessage {
    /// 创建新的文本消息
    pub fn new_text_message(
        session_id: String,
        role: MessageRole,
        text: String,
    ) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            session_id,
            role,
            content: vec![MessageContent::Text { text }],
            timestamp: Utc::now(),
            metadata: None,
        }
    }

    /// 创建新的文件消息
    pub fn new_file_message(
        session_id: String,
        role: MessageRole,
        file_uri: String,
        mime_type: String,
        description: Option<String>,
    ) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            session_id,
            role,
            content: vec![MessageContent::File { file_uri, mime_type, description }],
            timestamp: Utc::now(),
            metadata: None,
        }
    }

    /// 创建混合内容消息
    pub fn new_mixed_message(
        session_id: String,
        role: MessageRole,
        content: Vec<MessageContent>,
    ) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            session_id,
            role,
            content,
            timestamp: Utc::now(),
            metadata: None,
        }
    }
}

impl ConversationSession {
    /// 创建新会话
    pub fn new(title: Option<String>) -> Self {
        let now = Utc::now();
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            title,
            created_at: now,
            updated_at: now,
            is_active: true,
            metadata: None,
        }
    }

    /// 更新会话标题
    pub fn update_title(&mut self, title: Option<String>) {
        self.title = title;
        self.updated_at = Utc::now();
    }

    /// 标记会话为非活跃状态
    pub fn deactivate(&mut self) {
        self.is_active = false;
        self.updated_at = Utc::now();
    }
}

/// 会话统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationStats {
    pub total_sessions: u32,
    pub active_sessions: u32,
    pub total_messages: u32,
    pub average_messages_per_session: f64,
}

/// 会话清理配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationCleanupConfig {
    pub max_inactive_days: u32,
    pub max_messages_per_session: u32,
    pub auto_cleanup_enabled: bool,
}

impl Default for ConversationCleanupConfig {
    fn default() -> Self {
        Self {
            max_inactive_days: 30,
            max_messages_per_session: 1000,
            auto_cleanup_enabled: true,
        }
    }
}
