use tauri::{command, State};

use crate::app_state::AppState;
use crate::business::services::conversation_service::ConversationService;
use crate::data::models::conversation::{
    ConversationSession, ConversationMessage, ConversationHistory,
    CreateConversationSessionRequest, AddMessageRequest, ConversationHistoryQuery,
    MultiTurnConversationRequest, MultiTurnConversationResponse, ConversationStats,
};

/// 创建新会话
#[command]
pub async fn create_conversation_session(
    state: State<'_, AppState>,
    request: CreateConversationSessionRequest,
) -> Result<ConversationSession, String> {
    println!("🆕 创建新会话: {:?}", request.title);

    let conversation_service = {
        let app_state = state.inner();
        let conversation_repo = app_state.get_conversation_repository()
            .map_err(|e| format!("获取会话仓库失败: {}", e))?;
        ConversationService::new(conversation_repo)
    };

    conversation_service
        .create_session(request)
        .await
        .map_err(|e| {
            eprintln!("创建会话失败: {}", e);
            format!("创建会话失败: {}", e)
        })
}

/// 获取会话信息
#[command]
pub async fn get_conversation_session(
    state: State<'_, AppState>,
    session_id: String,
) -> Result<Option<ConversationSession>, String> {
    println!("📖 获取会话信息: {}", session_id);

    let conversation_service = {
        let app_state = state.inner();
        let conversation_repo = app_state.get_conversation_repository()
            .map_err(|e| format!("获取会话仓库失败: {}", e))?;
        ConversationService::new(conversation_repo)
    };

    conversation_service
        .get_session(&session_id)
        .await
        .map_err(|e| {
            eprintln!("获取会话信息失败: {}", e);
            format!("获取会话信息失败: {}", e)
        })
}

/// 获取会话历史
#[command]
pub async fn get_conversation_history(
    state: State<'_, AppState>,
    query: ConversationHistoryQuery,
) -> Result<ConversationHistory, String> {
    println!("📚 获取会话历史: {}", query.session_id);

    let conversation_service = {
        let app_state = state.inner();
        let conversation_repo = app_state.get_conversation_repository()
            .map_err(|e| format!("获取会话仓库失败: {}", e))?;
        ConversationService::new(conversation_repo)
    };

    conversation_service
        .get_conversation_history(query)
        .await
        .map_err(|e| {
            eprintln!("获取会话历史失败: {}", e);
            format!("获取会话历史失败: {}", e)
        })
}

/// 获取会话列表
#[command]
pub async fn get_conversation_sessions(
    state: State<'_, AppState>,
    limit: Option<u32>,
    offset: Option<u32>,
) -> Result<Vec<ConversationSession>, String> {
    println!("📋 获取会话列表: limit={:?}, offset={:?}", limit, offset);

    let conversation_service = {
        let app_state = state.inner();
        let conversation_repo = app_state.get_conversation_repository()
            .map_err(|e| format!("获取会话仓库失败: {}", e))?;
        ConversationService::new(conversation_repo)
    };

    conversation_service
        .get_sessions(limit, offset)
        .await
        .map_err(|e| {
            eprintln!("获取会话列表失败: {}", e);
            format!("获取会话列表失败: {}", e)
        })
}

/// 删除会话
#[command]
pub async fn delete_conversation_session(
    state: State<'_, AppState>,
    session_id: String,
) -> Result<(), String> {
    println!("🗑️ 删除会话: {}", session_id);

    let conversation_service = {
        let app_state = state.inner();
        let conversation_repo = app_state.get_conversation_repository()
            .map_err(|e| format!("获取会话仓库失败: {}", e))?;
        ConversationService::new(conversation_repo)
    };

    conversation_service
        .delete_session(&session_id)
        .await
        .map_err(|e| {
            eprintln!("删除会话失败: {}", e);
            format!("删除会话失败: {}", e)
        })
}

/// 添加消息到会话
#[command]
pub async fn add_conversation_message(
    state: State<'_, AppState>,
    request: AddMessageRequest,
) -> Result<ConversationMessage, String> {
    println!("💬 添加消息到会话: {}", request.session_id);

    let conversation_service = {
        let app_state = state.inner();
        let conversation_repo = app_state.get_conversation_repository()
            .map_err(|e| format!("获取会话仓库失败: {}", e))?;
        ConversationService::new(conversation_repo)
    };

    conversation_service
        .add_message(request)
        .await
        .map_err(|e| {
            eprintln!("添加消息失败: {}", e);
            format!("添加消息失败: {}", e)
        })
}

/// 多轮对话处理
#[command]
pub async fn process_multi_turn_conversation(
    state: State<'_, AppState>,
    request: MultiTurnConversationRequest,
) -> Result<MultiTurnConversationResponse, String> {
    println!("🤖 处理多轮对话: {:?}", request.user_message);

    let conversation_service = {
        let app_state = state.inner();
        let conversation_repo = app_state.get_conversation_repository()
            .map_err(|e| format!("获取会话仓库失败: {}", e))?;
        ConversationService::new(conversation_repo)
    };

    conversation_service
        .process_multi_turn_conversation(request)
        .await
        .map_err(|e| {
            eprintln!("多轮对话处理失败: {}", e);
            format!("多轮对话处理失败: {}", e)
        })
}

/// 获取会话统计信息
#[command]
pub async fn get_conversation_stats(
    state: State<'_, AppState>,
) -> Result<ConversationStats, String> {
    println!("📊 获取会话统计信息");

    let conversation_service = {
        let app_state = state.inner();
        let conversation_repo = app_state.get_conversation_repository()
            .map_err(|e| format!("获取会话仓库失败: {}", e))?;
        ConversationService::new(conversation_repo)
    };

    conversation_service
        .get_conversation_stats()
        .await
        .map_err(|e| {
            eprintln!("获取会话统计失败: {}", e);
            format!("获取会话统计失败: {}", e)
        })
}

/// 清理过期会话
#[command]
pub async fn cleanup_expired_sessions(
    state: State<'_, AppState>,
    max_inactive_days: u32,
) -> Result<u32, String> {
    println!("🧹 清理过期会话: {}天", max_inactive_days);

    let conversation_service = {
        let app_state = state.inner();
        let conversation_repo = app_state.get_conversation_repository()
            .map_err(|e| format!("获取会话仓库失败: {}", e))?;
        ConversationService::new(conversation_repo)
    };

    conversation_service
        .cleanup_expired_sessions(max_inactive_days)
        .await
        .map_err(|e| {
            eprintln!("清理过期会话失败: {}", e);
            format!("清理过期会话失败: {}", e)
        })
}

/// 更新会话标题
#[command]
pub async fn update_session_title(
    state: State<'_, AppState>,
    session_id: String,
    title: Option<String>,
) -> Result<(), String> {
    println!("✏️ 更新会话标题: {} -> {:?}", session_id, title);

    let conversation_service = {
        let app_state = state.inner();
        let conversation_repo = app_state.get_conversation_repository()
            .map_err(|e| format!("获取会话仓库失败: {}", e))?;
        ConversationService::new(conversation_repo)
    };

    conversation_service
        .update_session_title(&session_id, title)
        .await
        .map_err(|e| {
            eprintln!("更新会话标题失败: {}", e);
            format!("更新会话标题失败: {}", e)
        })
}

/// 生成会话摘要
#[command]
pub async fn generate_session_summary(
    state: State<'_, AppState>,
    session_id: String,
) -> Result<String, String> {
    println!("📝 生成会话摘要: {}", session_id);

    let conversation_service = {
        let app_state = state.inner();
        let conversation_repo = app_state.get_conversation_repository()
            .map_err(|e| format!("获取会话仓库失败: {}", e))?;
        ConversationService::new(conversation_repo)
    };

    conversation_service
        .generate_session_summary(&session_id)
        .await
        .map_err(|e| {
            eprintln!("生成会话摘要失败: {}", e);
            format!("生成会话摘要失败: {}", e)
        })
}
