/**
 * Python CLI 命令封装
 * 将 python -m python_core.cli 封装成 Rust 命令
 */

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

#[derive(Debug, Serialize, Deserialize)]
pub struct PythonCliResponse {
    pub success: bool,
    pub message: String,
    pub data: Option<serde_json::Value>,
    pub output: Option<String>,
    pub error: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AuthLoginRequest {
    pub username_or_email: String,
    pub password: Option<String>,
    pub verbose: Option<bool>,
    pub json_output: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AuthRegisterRequest {
    pub username: String,
    pub email: String,
    pub display_name: Option<String>,
    pub password: Option<String>,
    pub verbose: Option<bool>,
    pub json_output: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AuthVerifyRequest {
    pub token: String,
    pub verbose: Option<bool>,
}

/// 执行Python CLI命令的通用函数
async fn execute_python_cli_command(
    app: AppHandle,
    command_args: Vec<String>,
    config: Option<PythonExecutorConfig>,
) -> Result<PythonCliResponse, String> {
    // 构建完整的命令参数
    let mut args = vec!["-m".to_string(), "python_core.cli".to_string()];
    args.extend(command_args);

    println!("Executing Python CLI: python {}", args.join(" "));

    match execute_python_command(app, &args, config).await {
        Ok(output) => {
            // 尝试解析JSON响应
            if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(&output) {
                Ok(PythonCliResponse {
                    success: true,
                    message: "命令执行成功".to_string(),
                    data: Some(json_value),
                    output: Some(output),
                    error: None,
                })
            } else {
                // 如果不是JSON，直接返回文本输出
                Ok(PythonCliResponse {
                    success: true,
                    message: "命令执行成功".to_string(),
                    data: None,
                    output: Some(output),
                    error: None,
                })
            }
        }
        Err(error) => {
            Ok(PythonCliResponse {
                success: false,
                message: "命令执行失败".to_string(),
                data: None,
                output: None,
                error: Some(error),
            })
        }
    }
}

/// 用户登录
#[command]
pub async fn python_cli_auth_login(
    app: AppHandle,
    request: AuthLoginRequest,
) -> Result<PythonCliResponse, String> {
    let mut args = vec!["auth".to_string(), "login".to_string(), request.username_or_email];

    if let Some(password) = request.password {
        args.push("--password".to_string());
        args.push(password);
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(false) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args, None).await
}

/// 用户注册
#[command]
pub async fn python_cli_auth_register(
    app: AppHandle,
    request: AuthRegisterRequest,
) -> Result<PythonCliResponse, String> {
    let mut args = vec!["auth".to_string(), "register".to_string(), request.username, request.email];

    if let Some(display_name) = request.display_name {
        args.push("--display-name".to_string());
        args.push(display_name);
    }

    if let Some(password) = request.password {
        args.push("--password".to_string());
        args.push(password);
    }

    execute_python_cli_command(app, args, None).await
}

/// 验证Token
#[command]
pub async fn python_cli_auth_verify(
    app: AppHandle,
    request: AuthVerifyRequest,
) -> Result<PythonCliResponse, String> {
    let mut args = vec!["auth".to_string(), "verify".to_string(), request.token];

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    execute_python_cli_command(app, args, None).await
}

/// 获取用户列表
#[command]
pub async fn python_cli_auth_list(
    app: AppHandle,
    include_inactive: Option<bool>,
    limit: Option<i32>,
    verbose: Option<bool>,
) -> Result<PythonCliResponse, String> {
    let mut args = vec!["auth".to_string(), "list".to_string()];

    if include_inactive.unwrap_or(false) {
        args.push("--include-inactive".to_string());
    }

    if let Some(limit_val) = limit {
        args.push("--limit".to_string());
        args.push(limit_val.to_string());
    }

    if verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    execute_python_cli_command(app, args, None).await
}

/// 获取用户统计信息
#[command]
pub async fn python_cli_auth_stats(app: AppHandle) -> Result<PythonCliResponse, String> {
    let args = vec!["auth".to_string(), "stats".to_string()];
    execute_python_cli_command(app, args, None).await
}

/// 获取模板列表
#[command]
pub async fn python_cli_template_list(
    app: AppHandle,
    limit: Option<i32>,
    verbose: Option<bool>,
) -> Result<PythonCliResponse, String> {
    let mut args = vec!["template".to_string(), "list".to_string()];

    if let Some(limit_val) = limit {
        args.push("--limit".to_string());
        args.push(limit_val.to_string());
    }

    if verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    execute_python_cli_command(app, args, None).await
}

/// 批量导入模板
#[command]
pub async fn python_cli_template_batch_import(
    app: AppHandle,
    folder_path: String,
    verbose: Option<bool>,
) -> Result<PythonCliResponse, String> {
    let mut args = vec!["template".to_string(), "batch-import".to_string(), folder_path];

    if verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    execute_python_cli_command(app, args, None).await
}

/// 获取分类列表
#[command]
pub async fn python_cli_category_list(
    app: AppHandle,
    verbose: Option<bool>,
) -> Result<PythonCliResponse, String> {
    let mut args = vec!["category".to_string(), "list".to_string()];

    if verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    execute_python_cli_command(app, args, None).await
}

/// 场景检测
#[command]
pub async fn python_cli_scene_detect(
    app: AppHandle,
    video_path: String,
    threshold: Option<f64>,
    min_scene_len: Option<f64>,
    output_dir: Option<String>,
) -> Result<PythonCliResponse, String> {
    let mut args = vec!["scene".to_string(), "detect".to_string(), video_path];

    if let Some(threshold_val) = threshold {
        args.push("--threshold".to_string());
        args.push(threshold_val.to_string());
    }

    if let Some(min_len) = min_scene_len {
        args.push("--min-scene-len".to_string());
        args.push(min_len.to_string());
    }

    if let Some(output) = output_dir {
        args.push("--output".to_string());
        args.push(output);
    }

    execute_python_cli_command(app, args, None).await
}

/// 执行任意Python CLI命令
#[command]
pub async fn python_cli_execute(
    app: AppHandle,
    command_args: Vec<String>,
) -> Result<PythonCliResponse, String> {
    execute_python_cli_command(app, command_args, None).await
}
