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

#[derive(Debug, Serialize, Deserialize)]
pub struct CreateCategoryRequest {
    pub title: String,
    pub ai_prompt: String,
    pub color: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateCategoryRequest {
    pub title: Option<String>,
    pub ai_prompt: Option<String>,
    pub color: Option<String>,
    pub is_active: Option<bool>,
}

/// 获取所有资源分类
#[command]
pub async fn get_all_resource_categories(app: AppHandle) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.resource_category_manager".to_string(),
        "get_all_categories".to_string(),
    ];

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

/// 根据ID获取资源分类
#[command]
pub async fn get_resource_category_by_id(app: AppHandle, category_id: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.resource_category_manager".to_string(),
        "get_category_by_id".to_string(),
        category_id,
    ];

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

/// 创建新的资源分类
#[command]
pub async fn create_resource_category(app: AppHandle, request: CreateCategoryRequest) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.resource_category_manager".to_string(),
        "create_category".to_string(),
        request.title,
        request.ai_prompt,
        request.color,
    ];

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

/// 更新资源分类
#[command]
pub async fn update_resource_category(
    app: AppHandle,
    category_id: String,
    request: UpdateCategoryRequest,
) -> 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.resource_category_manager".to_string(),
        "update_category".to_string(),
        category_id,
        request_json,
    ];

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

/// 删除资源分类
#[command]
pub async fn delete_resource_category(app: AppHandle, category_id: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.resource_category_manager".to_string(),
        "delete_category".to_string(),
        category_id,
    ];

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

/// 搜索资源分类
#[command]
pub async fn search_resource_categories(app: AppHandle, keyword: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.resource_category_manager".to_string(),
        "search_categories".to_string(),
        keyword,
    ];

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