use serde::{Deserialize, Serialize};
use tauri::{command, AppHandle};
use crate::python_executor::execute_python_command;
use crate::command_utils::configure_system_command;

#[derive(Debug, Serialize, Deserialize)]
pub struct ProjectInfo {
    pub name: String,
    pub path: String,
    pub created_at: String,
    pub modified_at: String,
    pub video_tracks: Vec<VideoTrack>,
    pub audio_tracks: Vec<AudioTrack>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct VideoTrack {
    pub id: String,
    pub name: String,
    pub file_path: String,
    pub duration: f64,
    pub start_time: f64,
    pub end_time: f64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AudioTrack {
    pub id: String,
    pub name: String,
    pub file_path: String,
    pub duration: f64,
    pub start_time: f64,
    pub end_time: f64,
    pub volume: f64,
}

#[tauri::command]
pub async fn get_project_info(project_path: String) -> Result<ProjectInfo, String> {
    println!("Getting project info for: {}", project_path);
    
    // For now, return a mock project
    // In a real implementation, you would load this from a project file
    let project_info = ProjectInfo {
        name: "Sample Project".to_string(),
        path: project_path,
        created_at: "2024-01-01T00:00:00Z".to_string(),
        modified_at: "2024-01-01T00:00:00Z".to_string(),
        video_tracks: vec![],
        audio_tracks: vec![],
    };
    
    Ok(project_info)
}



/// 扫描目录文件
#[command]
pub async fn scan_directory(app: AppHandle, directory_path: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.file_manager".to_string(),
        "scan_directory".to_string(),
        directory_path,
    ];

    execute_python_command(app, &args, None).await
}

/// 在系统中打开文件
#[command]
pub async fn open_file_in_system(file_path: String) -> Result<(), String> {
    #[cfg(target_os = "windows")]
    {
        let mut cmd = std::process::Command::new("cmd");
        cmd.args(["/C", "start", "", &file_path]);

        // Configure console window hiding
        configure_system_command(&mut cmd);

        cmd.spawn()
            .map_err(|e| format!("Failed to open file: {}", e))?;
    }

    #[cfg(target_os = "macos")]
    {
        std::process::Command::new("open")
            .arg(&file_path)
            .spawn()
            .map_err(|e| format!("Failed to open file: {}", e))?;
    }

    #[cfg(target_os = "linux")]
    {
        std::process::Command::new("xdg-open")
            .arg(&file_path)
            .spawn()
            .map_err(|e| format!("Failed to open file: {}", e))?;
    }

    Ok(())
}

/// 删除文件
#[command]
pub async fn delete_file(file_path: String) -> Result<(), String> {
    std::fs::remove_file(&file_path)
        .map_err(|e| format!("Failed to delete file: {}", e))
}

#[tauri::command]
pub async fn save_project(project_info: ProjectInfo) -> Result<String, String> {
    println!("Saving project: {}", project_info.name);
    
    // For now, just return success
    // In a real implementation, you would save the project to a file
    Ok(format!("Project '{}' saved successfully", project_info.name))
}

#[tauri::command]
pub async fn load_project(project_path: String) -> Result<ProjectInfo, String> {
    println!("Loading project from: {}", project_path);
    
    // For now, return a mock project
    // In a real implementation, you would load this from the project file
    let project_info = ProjectInfo {
        name: "Loaded Project".to_string(),
        path: project_path,
        created_at: "2024-01-01T00:00:00Z".to_string(),
        modified_at: "2024-01-01T00:00:00Z".to_string(),
        video_tracks: vec![],
        audio_tracks: vec![],
    };
    
    Ok(project_info)
}

// 项目管理相关结构体和命令

#[derive(Debug, Serialize, Deserialize)]
pub struct CreateProjectRequest {
    pub name: String,
    pub local_directory: String,
    pub product_name: Option<String>,
    pub product_image: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateProjectRequest {
    pub name: Option<String>,
    pub local_directory: Option<String>,
    pub product_name: Option<String>,
    pub product_image: Option<String>,
}

/// 获取所有项目
#[command]
pub async fn get_all_projects(app: AppHandle) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.project_manager".to_string(),
        "get_all_projects".to_string(),
    ];

    execute_python_command(app, &args, None).await
}

/// 根据ID获取项目
#[command]
pub async fn get_project_by_id(app: AppHandle, project_id: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.project_manager".to_string(),
        "get_project_by_id".to_string(),
        project_id,
    ];

    execute_python_command(app, &args, None).await
}

/// 创建新项目
#[command]
pub async fn create_project(app: AppHandle, request: CreateProjectRequest) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.project_manager".to_string(),
        "create_project".to_string(),
        request.name,
        request.local_directory,
        request.product_name.unwrap_or_default(),
        request.product_image.unwrap_or_default(),
    ];

    execute_python_command(app, &args, None).await
}

/// 更新项目
#[command]
pub async fn update_project(
    app: AppHandle,
    project_id: String,
    request: UpdateProjectRequest,
) -> Result<String, String> {
    let request_json = serde_json::to_string(&request)
        .map_err(|e| format!("Failed to serialize request: {}", e))?;

    let args = vec![
        "-m".to_string(),
        "python_core.services.project_manager".to_string(),
        "update_project".to_string(),
        project_id,
        request_json,
    ];

    execute_python_command(app, &args, None).await
}

/// 删除项目
#[command]
pub async fn delete_project(app: AppHandle, project_id: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.project_manager".to_string(),
        "delete_project".to_string(),
        project_id,
    ];

    execute_python_command(app, &args, None).await
}

/// 搜索项目
#[command]
pub async fn search_projects(app: AppHandle, keyword: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.project_manager".to_string(),
        "search_projects".to_string(),
        keyword,
    ];

    execute_python_command(app, &args, None).await
}

/// 打开项目目录
#[command]
pub async fn open_project_directory(app: AppHandle, project_id: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.project_manager".to_string(),
        "open_project_directory".to_string(),
        project_id,
    ];

    execute_python_command(app, &args, None).await
}
