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

#[derive(Debug, Serialize, Deserialize)]
pub struct CreateModelRequest {
    pub model_number: String,
    pub model_image: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateModelRequest {
    pub model_number: Option<String>,
    pub model_image: Option<String>,
}

/// 获取所有模特
#[command]
pub async fn get_all_models(app: AppHandle) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.model_manager".to_string(),
        "get_all_models".to_string(),
    ];
    
    execute_python_command(app, &args, None).await
}

/// 根据ID获取模特
#[command]
pub async fn get_model_by_id(app: AppHandle, model_id: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.model_manager".to_string(),
        "get_model_by_id".to_string(),
        model_id,
    ];
    
    execute_python_command(app, &args, None).await
}

/// 创建新模特
#[command]
pub async fn create_model(app: AppHandle, request: CreateModelRequest) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.model_manager".to_string(),
        "create_model".to_string(),
        request.model_number,
        request.model_image.unwrap_or_default(),
    ];
    
    execute_python_command(app, &args, None).await
}

/// 更新模特
#[command]
pub async fn update_model(
    app: AppHandle,
    model_id: String,
    request: UpdateModelRequest,
) -> 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.model_manager".to_string(),
        "update_model".to_string(),
        model_id,
        request_json,
    ];
    
    execute_python_command(app, &args, None).await
}

/// 删除模特
#[command]
pub async fn delete_model(app: AppHandle, model_id: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.model_manager".to_string(),
        "delete_model".to_string(),
        model_id,
    ];
    
    execute_python_command(app, &args, None).await
}

/// 搜索模特
#[command]
pub async fn search_models(app: AppHandle, keyword: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.model_manager".to_string(),
        "search_models".to_string(),
        keyword,
    ];
    
    execute_python_command(app, &args, None).await
}
