use crate::app_state::AppState;
use tauri::State;

/// 初始化数据库
/// 遵循 Tauri 开发规范的命令设计模式
#[tauri::command]
pub fn initialize_database(state: State<AppState>) -> Result<(), String> {
    state.initialize_database().map_err(|e| e.to_string())
}

/// 检查数据库连接状态
/// 用于诊断数据库连接问题
#[tauri::command]
pub fn check_database_connection(state: State<AppState>) -> Result<String, String> {
    let database_guard = state.database.lock().map_err(|e| format!("获取数据库失败: {}", e))?;
    let database = database_guard.as_ref().ok_or("数据库未初始化")?;
    
    Ok(database.check_connection_status())
}

/// 强制释放数据库连接
/// 紧急情况下使用，可能导致数据不一致
#[tauri::command]
pub fn force_release_database_connection(state: State<AppState>) -> Result<String, String> {
    println!("警告：强制释放数据库连接");

    // 重新初始化数据库连接
    match state.initialize_database() {
        Ok(_) => Ok("数据库连接已重新初始化".to_string()),
        Err(e) => Err(format!("重新初始化数据库失败: {}", e))
    }
}

/// 获取连接池统计信息
#[tauri::command]
pub fn get_connection_pool_stats(state: State<AppState>) -> Result<String, String> {
    let database_guard = state.database.lock().map_err(|e| format!("获取数据库失败: {}", e))?;
    let database = database_guard.as_ref().ok_or("数据库未初始化")?;

    if !database.has_pool() {
        return Ok("数据库未启用连接池".to_string());
    }

    match database.try_acquire_from_pool() {
        Ok(Some(_)) => Ok("连接池状态：有可用连接".to_string()),
        Ok(None) => Ok("连接池状态：无可用连接".to_string()),
        Err(e) => Err(format!("获取连接池状态失败: {}", e)),
    }
}

/// 测试连接池初始化
#[tauri::command]
pub fn test_connection_pool_init(_state: State<AppState>) -> Result<String, String> {
    use crate::infrastructure::database::Database;

    println!("开始测试连接池初始化...");

    match Database::new_with_pool() {
        Ok(db) => {
            println!("连接池初始化成功");
            if db.has_pool() {
                Ok("连接池测试成功：连接池已启用".to_string())
            } else {
                Ok("连接池测试警告：连接池未启用".to_string())
            }
        },
        Err(e) => {
            eprintln!("连接池初始化失败: {}", e);
            Err(format!("连接池测试失败: {}", e))
        }
    }
}

/// 调试数据库数据
#[tauri::command]
pub fn debug_database_data(state: State<AppState>, project_id: String) -> Result<String, String> {
    let database_guard = state.database.lock().map_err(|e| format!("获取数据库失败: {}", e))?;
    let database = database_guard.as_ref().ok_or("数据库未初始化")?;

    let conn = database.get_connection();
    let conn = conn.lock().map_err(|e| format!("获取连接失败: {}", e))?;

    let mut result = String::new();

    // 检查项目表
    match conn.prepare("SELECT COUNT(*) FROM projects WHERE id = ?1") {
        Ok(mut stmt) => {
            match stmt.query_row([&project_id], |row| row.get::<_, i64>(0)) {
                Ok(count) => result.push_str(&format!("项目记录数: {}\n", count)),
                Err(e) => result.push_str(&format!("查询项目失败: {}\n", e)),
            }
        },
        Err(e) => result.push_str(&format!("准备项目查询失败: {}\n", e)),
    }

    // 检查素材表
    match conn.prepare("SELECT COUNT(*) FROM materials WHERE project_id = ?1") {
        Ok(mut stmt) => {
            match stmt.query_row([&project_id], |row| row.get::<_, i64>(0)) {
                Ok(count) => result.push_str(&format!("素材记录数: {}\n", count)),
                Err(e) => result.push_str(&format!("查询素材失败: {}\n", e)),
            }
        },
        Err(e) => result.push_str(&format!("准备素材查询失败: {}\n", e)),
    }

    // 检查片段表
    match conn.prepare("SELECT COUNT(*) FROM material_segments ms JOIN materials m ON ms.material_id = m.id WHERE m.project_id = ?1") {
        Ok(mut stmt) => {
            match stmt.query_row([&project_id], |row| row.get::<_, i64>(0)) {
                Ok(count) => result.push_str(&format!("片段记录数: {}\n", count)),
                Err(e) => result.push_str(&format!("查询片段失败: {}\n", e)),
            }
        },
        Err(e) => result.push_str(&format!("准备片段查询失败: {}\n", e)),
    }

    // 列出素材详情
    match conn.prepare("SELECT id, name, processing_status, material_type FROM materials WHERE project_id = ?1 LIMIT 5") {
        Ok(mut stmt) => {
            result.push_str("\n素材详情（前5个）:\n");
            match stmt.query_map([&project_id], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                ))
            }) {
                Ok(rows) => {
                    for (i, row) in rows.enumerate() {
                        match row {
                            Ok((id, name, status, material_type)) => {
                                result.push_str(&format!("  {}. {} ({}) - 状态: {} - 类型: {}\n", i + 1, name, id, status, material_type));

                                // 查询每个素材的片段数量
                                match conn.prepare("SELECT COUNT(*) FROM material_segments WHERE material_id = ?1") {
                                    Ok(mut seg_stmt) => {
                                        match seg_stmt.query_row([&id], |row| row.get::<_, i64>(0)) {
                                            Ok(seg_count) => result.push_str(&format!("     片段数: {}\n", seg_count)),
                                            Err(e) => result.push_str(&format!("     查询片段数失败: {}\n", e)),
                                        }
                                    },
                                    Err(e) => result.push_str(&format!("     准备片段查询失败: {}\n", e)),
                                }
                            },
                            Err(e) => result.push_str(&format!("  解析素材行失败: {}\n", e)),
                        }
                    }
                },
                Err(e) => result.push_str(&format!("查询素材详情失败: {}\n", e)),
            }
        },
        Err(e) => result.push_str(&format!("准备素材详情查询失败: {}\n", e)),
    }

    Ok(result)
}


