use tauri::{command, State};
use crate::app_state::AppState;
use crate::infrastructure::bowong_text_video_agent_service::BowongTextVideoAgentService;
use crate::data::models::bowong_text_video_agent::*;
use crate::infrastructure::event_bus::EventBusManager;
use crate::data::repositories::hedra_lipsync_repository::HedraLipSyncRepository;
use std::sync::Arc;


/// BowongTextVideoAgent 服务的全局状态


/// 初始化 BowongTextVideoAgent 服务
#[command]
pub async fn initialize_bowong_service(
    state: State<'_, AppState>,
    config: BowongTextVideoAgentConfig,
) -> Result<String, String> {
    state.initialize_bowong_service(config)
        .map_err(|e| format!("Failed to initialize BowongTextVideoAgent service: {}", e))?;

    Ok("BowongTextVideoAgent service initialized successfully".to_string())
}

// ============================================================================
// 提示词预处理模块命令
// ============================================================================

/// 获取示例提示词
#[command]
pub async fn bowong_get_sample_prompt() -> Result<ApiResponse, String> {
    // 这里需要从全局状态获取服务实例
    // 暂时返回模拟数据
    Ok(ApiResponse {
        status: true,
        message: "Sample prompt retrieved".to_string(),
        data: Some(serde_json::json!({
            "prompt": "a beautiful landscape with mountains and lakes"
        })),
    })
}

/// 健康检查
#[command]
pub async fn bowong_health_check() -> Result<ApiResponse, String> {
    Ok(ApiResponse {
        status: true,
        message: "Service is healthy".to_string(),
        data: None,
    })
}

// ============================================================================
// 文件操作模块命令
// ============================================================================

/// 上传文件到 S3
#[command]
pub async fn bowong_upload_file_to_s3(
    request: S3FileUploadRequest,
) -> Result<FileUploadResponse, String> {
    // 实际实现需要调用服务
    Ok(FileUploadResponse {
        status: true,
        msg: "File uploaded successfully".to_string(),
        data: Some("https://s3.example.com/uploaded-file.jpg".to_string()),
    })
}

/// 上传文件到 COS
#[command]
pub async fn bowong_upload_file(
    request: COSFileUploadRequest,
) -> Result<FileUploadResponse, String> {
    Ok(FileUploadResponse {
        status: true,
        msg: "File uploaded successfully".to_string(),
        data: Some("https://cos.example.com/uploaded-file.jpg".to_string()),
    })
}

/// 文件健康检查
#[command]
pub async fn bowong_file_health_check() -> Result<ApiResponse, String> {
    Ok(ApiResponse {
        status: true,
        message: "File service is healthy".to_string(),
        data: None,
    })
}

// ============================================================================
// 视频模板管理模块命令
// ============================================================================

/// 获取模板列表
#[command]
pub async fn bowong_get_templates(
    request: TemplateListRequest,
) -> Result<TemplateListResponse, String> {
    Ok(TemplateListResponse {
        templates: vec![],
        total: 0,
        page: request.page.unwrap_or(1),
        page_size: request.page_size.unwrap_or(10),
    })
}

/// 获取单个模板
#[command]
pub async fn bowong_get_template(
    template_id: String,
) -> Result<VideoTemplate, String> {
    Ok(VideoTemplate {
        id: template_id,
        name: "Sample Template".to_string(),
        description: Some("A sample video template".to_string()),
        config: serde_json::json!({}),
        created_at: "2024-01-01T00:00:00Z".to_string(),
        updated_at: "2024-01-01T00:00:00Z".to_string(),
    })
}

/// 创建模板
#[command]
pub async fn bowong_create_template(
    request: CreateTemplateRequest,
) -> Result<VideoTemplate, String> {
    Ok(VideoTemplate {
        id: "new-template-id".to_string(),
        name: request.name,
        description: request.description,
        config: request.config,
        created_at: "2024-01-01T00:00:00Z".to_string(),
        updated_at: "2024-01-01T00:00:00Z".to_string(),
    })
}

/// 更新模板
#[command]
pub async fn bowong_update_template(
    request: UpdateTemplateRequest,
) -> Result<VideoTemplate, String> {
    Ok(VideoTemplate {
        id: request.id,
        name: request.name.unwrap_or("Updated Template".to_string()),
        description: request.description,
        config: request.config.unwrap_or(serde_json::json!({})),
        created_at: "2024-01-01T00:00:00Z".to_string(),
        updated_at: "2024-01-01T00:00:00Z".to_string(),
    })
}

/// 删除模板
#[command]
pub async fn bowong_delete_template(
    template_id: String,
) -> Result<ApiResponse, String> {
    Ok(ApiResponse {
        status: true,
        message: format!("Template {} deleted successfully", template_id),
        data: None,
    })
}

// ============================================================================
// Midjourney 图片生成模块命令
// ============================================================================

/// 检查提示词
#[command]
pub async fn bowong_check_prompt(
    params: PromptCheckParams,
) -> Result<ApiResponse, String> {
    Ok(ApiResponse {
        status: true,
        message: "Prompt is valid".to_string(),
        data: Some(serde_json::json!({
            "prompt": params.prompt,
            "valid": true
        })),
    })
}

/// 同步生成图片
#[command]
pub async fn bowong_sync_generate_image(
    request: SyncImageGenerationRequest,
) -> Result<ImageGenerationResponse, String> {
    Ok(ImageGenerationResponse {
        task_id: "img-task-123".to_string(),
        status: "completed".to_string(),
        images: Some(vec![
            "https://example.com/generated-image-1.jpg".to_string(),
            "https://example.com/generated-image-2.jpg".to_string(),
        ]),
        error: None,
    })
}

/// 异步生成图片
#[command]
pub async fn bowong_async_generate_image(
    request: AsyncImageGenerationRequest,
) -> Result<TaskResponse, String> {
    Ok(TaskResponse {
        status: true,
        data: "img-task-456".to_string(),
        msg: "Image generation task submitted".to_string(),
    })
}

/// 描述图片
#[command]
pub async fn bowong_describe_image(
    request: ImageDescribeRequest,
) -> Result<ApiResponse, String> {
    Ok(ApiResponse {
        status: true,
        message: "Image described successfully".to_string(),
        data: Some(serde_json::json!({
            "description": "A beautiful landscape with mountains and lakes"
        })),
    })
}

// ============================================================================
// 极梦视频生成模块命令
// ============================================================================

/// 生成视频
#[command]
pub async fn bowong_generate_video(
    request: VideoGenerationRequest,
) -> Result<VideoGenerationResponse, String> {
    Ok(VideoGenerationResponse {
        task_id: "video-task-789".to_string(),
        status: "completed".to_string(),
        video_url: Some("https://example.com/generated-video.mp4".to_string()),
        progress: Some(100.0),
        error: None,
    })
}

/// 批量查询视频状态
#[command]
pub async fn bowong_batch_query_video_status(
    request: VideoTaskStatus,
) -> Result<BatchVideoStatusResponse, String> {
    let results = request.task_ids.into_iter().map(|task_id| {
        TaskStatusResponse {
            task_id,
            status: "completed".to_string(),
            progress: Some(100.0),
            result: Some(serde_json::json!({
                "video_url": "https://example.com/video.mp4"
            })),
            error: None,
            created_at: Some("2024-01-01T00:00:00Z".to_string()),
            updated_at: Some("2024-01-01T00:00:00Z".to_string()),
        }
    }).collect();

    Ok(BatchVideoStatusResponse { results })
}

// ============================================================================
// 任务管理模块命令
// ============================================================================

/// 创建任务
#[command]
pub async fn bowong_create_task(
    request: TaskRequest,
) -> Result<TaskResponse, String> {
    Ok(TaskResponse {
        status: true,
        data: "task-abc123".to_string(),
        msg: "Task created successfully".to_string(),
    })
}

/// 获取任务状态
#[command]
pub async fn bowong_get_task_status(
    task_id: String,
) -> Result<TaskStatusResponse, String> {
    Ok(TaskStatusResponse {
        task_id,
        status: "completed".to_string(),
        progress: Some(100.0),
        result: Some(serde_json::json!({
            "output": "Task completed successfully"
        })),
        error: None,
        created_at: Some("2024-01-01T00:00:00Z".to_string()),
        updated_at: Some("2024-01-01T00:00:00Z".to_string()),
    })
}

/// 检查任务类型
#[command]
pub async fn bowong_check_task_type(
    params: CheckTaskTypeParams,
) -> Result<ApiResponse, String> {
    Ok(ApiResponse {
        status: true,
        message: "Task type is valid".to_string(),
        data: Some(serde_json::json!({
            "task_type": params.task_type,
            "supported": true
        })),
    })
}

// ============================================================================
// 302AI 服务集成模块命令
// ============================================================================

/// 302AI MJ 异步生成图片
#[command]
pub async fn bowong_ai302_mj_async_generate_image(
    request: AI302MJImageRequest,
) -> Result<TaskResponse, String> {
    Ok(TaskResponse {
        status: true,
        data: "ai302-mj-task-123".to_string(),
        msg: "302AI MJ image generation task submitted".to_string(),
    })
}

/// 302AI MJ 取消任务
#[command]
pub async fn bowong_ai302_mj_cancel_task(
    request: AI302TaskCancelRequest,
) -> Result<ApiResponse, String> {
    Ok(ApiResponse {
        status: true,
        message: format!("Task {} cancelled successfully", request.task_id),
        data: None,
    })
}

/// 302AI MJ 查询任务状态
#[command]
pub async fn bowong_ai302_mj_query_task_status(
    params: AI302TaskStatusParams,
) -> Result<TaskStatusResponse, String> {
    Ok(TaskStatusResponse {
        task_id: params.task_id,
        status: "completed".to_string(),
        progress: Some(100.0),
        result: Some(serde_json::json!({
            "images": ["https://example.com/ai302-image.jpg"]
        })),
        error: None,
        created_at: Some("2024-01-01T00:00:00Z".to_string()),
        updated_at: Some("2024-01-01T00:00:00Z".to_string()),
    })
}

/// 302AI MJ 同步生成图片
#[command]
pub async fn bowong_ai302_mj_sync_generate_image(
    request: SyncImageGenerationRequest,
) -> Result<ImageGenerationResponse, String> {
    Ok(ImageGenerationResponse {
        task_id: "ai302-mj-sync-123".to_string(),
        status: "completed".to_string(),
        images: Some(vec!["https://example.com/ai302-sync-image.jpg".to_string()]),
        error: None,
    })
}

/// 302AI JM 同步生成视频
#[command]
pub async fn bowong_ai302_jm_sync_generate_video(
    request: AI302JMVideoRequest,
) -> Result<VideoGenerationResponse, String> {
    Ok(VideoGenerationResponse {
        task_id: "ai302-jm-video-123".to_string(),
        status: "completed".to_string(),
        video_url: Some("https://example.com/ai302-video.mp4".to_string()),
        progress: Some(100.0),
        error: None,
    })
}

/// 302AI JM 异步生成视频
#[command]
pub async fn bowong_ai302_jm_async_generate_video(
    request: AI302JMVideoRequest,
) -> Result<TaskResponse, String> {
    Ok(TaskResponse {
        status: true,
        data: "ai302-jm-async-456".to_string(),
        msg: "302AI JM video generation task submitted".to_string(),
    })
}

/// 302AI VEO 异步提交
#[command]
pub async fn bowong_ai302_veo_async_submit(
    request: AI302VEOVideoRequest,
) -> Result<TaskResponse, String> {
    Ok(TaskResponse {
        status: true,
        data: "ai302-veo-789".to_string(),
        msg: "302AI VEO video task submitted".to_string(),
    })
}

/// 302AI VEO 同步生成视频
#[command]
pub async fn bowong_ai302_veo_sync_generate_video(
    request: AI302VEOVideoRequest,
) -> Result<VideoGenerationResponse, String> {
    Ok(VideoGenerationResponse {
        task_id: "ai302-veo-sync-101".to_string(),
        status: "completed".to_string(),
        video_url: Some("https://example.com/ai302-veo-video.mp4".to_string()),
        progress: Some(100.0),
        error: None,
    })
}

// ============================================================================
// 海螺API模块命令
// ============================================================================

/// 生成语音
#[command]
pub async fn bowong_generate_speech(
    request: SpeechGenerationRequest,
) -> Result<ApiResponse, String> {
    Ok(ApiResponse {
        status: true,
        message: "Speech generated successfully".to_string(),
        data: Some(serde_json::json!({
            "audio_url": "https://example.com/generated-speech.mp3"
        })),
    })
}

/// 获取声音列表
#[command]
pub async fn bowong_get_voices() -> Result<VoiceListResponse, String> {
    Ok(VoiceListResponse {
        voices: vec![
            VoiceInfo {
                id: "voice-1".to_string(),
                name: "Female Voice 1".to_string(),
                language: "zh-CN".to_string(),
                gender: "female".to_string(),
            },
            VoiceInfo {
                id: "voice-2".to_string(),
                name: "Male Voice 1".to_string(),
                language: "zh-CN".to_string(),
                gender: "male".to_string(),
            },
        ],
    })
}

/// 上传音频文件
#[command]
pub async fn bowong_upload_audio_file(
    request: AudioFileUploadRequest,
) -> Result<FileUploadResponse, String> {
    Ok(FileUploadResponse {
        status: true,
        msg: "Audio file uploaded successfully".to_string(),
        data: Some("https://example.com/uploaded-audio.mp3".to_string()),
    })
}

/// 克隆声音
#[command]
pub async fn bowong_clone_voice(
    request: VoiceCloneRequest,
) -> Result<ApiResponse, String> {
    Ok(ApiResponse {
        status: true,
        message: "Voice cloned successfully".to_string(),
        data: Some(serde_json::json!({
            "voice_id": "cloned-voice-456",
            "voice_name": request.voice_name
        })),
    })
}

// ============================================================================
// 聚合接口模块命令
// ============================================================================

/// 获取图片模型列表
#[command]
pub async fn bowong_get_image_model_list() -> Result<ModelListResponse, String> {
    Ok(ModelListResponse {
        models: vec![
            ModelInfo {
                id: "midjourney".to_string(),
                name: "Midjourney".to_string(),
                description: Some("AI image generation model".to_string()),
                capabilities: vec!["image_generation".to_string(), "image_variation".to_string()],
            },
            ModelInfo {
                id: "dalle3".to_string(),
                name: "DALL-E 3".to_string(),
                description: Some("OpenAI's image generation model".to_string()),
                capabilities: vec!["image_generation".to_string()],
            },
        ],
    })
}

/// 聚合同步生成图片
#[command]
pub async fn bowong_union_sync_generate_image(
    request: UnionImageGenerationRequest,
) -> Result<ImageGenerationResponse, String> {
    Ok(ImageGenerationResponse {
        task_id: "union-img-123".to_string(),
        status: "completed".to_string(),
        images: Some(vec!["https://example.com/union-image.jpg".to_string()]),
        error: None,
    })
}

/// 获取视频模型列表
#[command]
pub async fn bowong_get_video_model_list() -> Result<ModelListResponse, String> {
    Ok(ModelListResponse {
        models: vec![
            ModelInfo {
                id: "jimeng".to_string(),
                name: "极梦".to_string(),
                description: Some("AI video generation model".to_string()),
                capabilities: vec!["video_generation".to_string()],
            },
            ModelInfo {
                id: "veo".to_string(),
                name: "VEO".to_string(),
                description: Some("Advanced video generation model".to_string()),
                capabilities: vec!["video_generation".to_string(), "video_editing".to_string()],
            },
        ],
    })
}

/// 聚合异步生成视频
#[command]
pub async fn bowong_union_async_generate_video(
    request: UnionVideoGenerationRequest,
) -> Result<TaskResponse, String> {
    Ok(TaskResponse {
        status: true,
        data: "union-video-456".to_string(),
        msg: "Union video generation task submitted".to_string(),
    })
}

// ============================================================================
// ComfyUI 工作流模块命令
// ============================================================================

/// 获取运行节点
#[command]
pub async fn bowong_get_running_node(
    _params: Option<GetRunningNodeParams>,
) -> Result<ApiResponse, String> {
    Ok(ApiResponse {
        status: true,
        message: "Running nodes retrieved".to_string(),
        data: Some(serde_json::json!({
            "nodes": [
                {"id": "node-1", "status": "running"},
                {"id": "node-2", "status": "idle"}
            ]
        })),
    })
}

/// 提交 ComfyUI 任务
#[command]
pub async fn bowong_submit_comfyui_task(
    _request: ComfyUITaskRequest,
) -> Result<TaskResponse, String> {
    Ok(TaskResponse {
        status: true,
        data: "comfyui-task-789".to_string(),
        msg: "ComfyUI task submitted".to_string(),
    })
}

/// 查询 ComfyUI 任务状态
#[command]
pub async fn bowong_query_comfyui_task_status(
    params: ComfyUITaskStatusParams,
) -> Result<TaskStatusResponse, String> {
    Ok(TaskStatusResponse {
        task_id: params.task_id,
        status: "completed".to_string(),
        progress: Some(100.0),
        result: Some(serde_json::json!({
            "output_images": ["https://example.com/comfyui-output.jpg"]
        })),
        error: None,
        created_at: Some("2024-01-01T00:00:00Z".to_string()),
        updated_at: Some("2024-01-01T00:00:00Z".to_string()),
    })
}

/// 同步执行工作流
#[command]
pub async fn bowong_sync_execute_workflow(
    request: ComfyUISyncExecuteRequest,
) -> Result<ApiResponse, String> {
    Ok(ApiResponse {
        status: true,
        message: "Workflow executed successfully".to_string(),
        data: Some(serde_json::json!({
            "execution_id": "exec-123",
            "outputs": ["https://example.com/workflow-output.jpg"]
        })),
    })
}

// ============================================================================
// 批量操作命令
// ============================================================================

/// 批量取消任务
#[command]
pub async fn bowong_cancel_tasks(
    task_ids: Vec<String>,
) -> Result<Vec<ApiResponse>, String> {
    let results = task_ids.into_iter().map(|task_id| {
        ApiResponse {
            status: true,
            message: format!("Task {} cancelled", task_id),
            data: None,
        }
    }).collect();

    Ok(results)
}

/// 批量查询任务状态
#[command]
pub async fn bowong_batch_query_task_status(
    task_ids: Vec<String>,
) -> Result<Vec<TaskStatusResponse>, String> {
    let results = task_ids.into_iter().map(|task_id| {
        TaskStatusResponse {
            task_id,
            status: "completed".to_string(),
            progress: Some(100.0),
            result: Some(serde_json::json!({"output": "success"})),
            error: None,
            created_at: Some("2024-01-01T00:00:00Z".to_string()),
            updated_at: Some("2024-01-01T00:00:00Z".to_string()),
        }
    }).collect();

    Ok(results)
}

/// 等待任务完成
#[command]
pub async fn bowong_wait_for_task_completion(
    state: State<'_, AppState>,
    task_id: String,
    max_wait_time: u64,
    poll_interval: u64,
) -> Result<TaskStatusResponse, String> {
    // 克隆服务以避免跨 await 点持有 MutexGuard
    let service = {
        let service_guard = state.get_bowong_service()
            .map_err(|e| format!("Failed to get BowongTextVideoAgent service: {}", e))?;

        service_guard.as_ref()
            .ok_or_else(|| "BowongTextVideoAgent service not initialized".to_string())?
            .clone()
    };

    // 使用真实的轮询逻辑等待任务完成
    service.wait_for_task_completion(&task_id, max_wait_time, poll_interval)
        .await
        .map_err(|e| format!("Failed to wait for task completion: {}", e))
}

// ============================================================================
// Hedra 口型合成模块命令
// ============================================================================

/// Hedra 上传文件
#[command]
pub async fn hedra_upload_file(
    state: State<'_, AppState>,
    params: HedraFileUploadRequest,
) -> Result<FileUploadResponse, String> {
    // 克隆服务以避免跨 await 点持有 MutexGuard
    let service = {
        let service_guard = state.get_bowong_service()
            .map_err(|e| format!("Failed to get BowongTextVideoAgent service: {}", e))?;

        service_guard.as_ref()
            .ok_or_else(|| "BowongTextVideoAgent service not initialized".to_string())?
            .clone()
    };

    service.hedra_upload_file(&params)
        .await
        .map_err(|e| format!("Failed to upload file to Hedra: {}", e))
}

/// Hedra 提交任务
#[command]
pub async fn hedra_submit_task(
    state: State<'_, AppState>,
    params: HedraTaskSubmitRequest,
) -> Result<TaskResponse, String> {
    println!("=== Hedra Submit Task Command ===");
    println!("接收到的参数: {:?}", params);
    println!("img_file: {:?}", params.img_file);
    println!("audio_file: {:?}", params.audio_file);
    println!("prompt: '{}'", params.prompt);
    println!("resolution: {}", params.resolution);
    println!("aspect_ratio: {}", params.aspect_ratio);
    println!("params 字段: {:?}", params.params);

    // 克隆服务以避免跨 await 点持有 MutexGuard
    let service = {
        let service_guard = state.get_bowong_service()
            .map_err(|e| format!("Failed to get BowongTextVideoAgent service: {}", e))?;

        service_guard.as_ref()
            .ok_or_else(|| "BowongTextVideoAgent service not initialized".to_string())?
            .clone()
    };

    println!("=== 调用服务方法 ===");
    let result = service.hedra_submit_task(&params)
        .await
        .map_err(|e| {
            println!("=== 服务调用失败 ===");
            println!("错误信息: {}", e);
            format!("Failed to submit Hedra task: {}", e)
        });

    if let Ok(ref response) = result {
        println!("=== 服务调用成功 ===");
        println!("响应: {:?}", response);
    }

    result
}

/// Hedra 异步提交任务（立即返回，后台轮询）
#[command]
pub async fn hedra_submit_task_async(
    state: State<'_, AppState>,
    record_id: String,
    params: HedraTaskSubmitRequest,
) -> Result<TaskResponse, String> {
    println!("=== Hedra Async Submit Task Command ===");
    println!("接收到的参数: {:?}", params);
    println!("记录ID: {}", record_id);

    // 克隆服务以避免跨 await 点持有 MutexGuard
    let service = {
        let service_guard = state.get_bowong_service()
            .map_err(|e| format!("Failed to get BowongTextVideoAgent service: {}", e))?;

        service_guard.as_ref()
            .ok_or_else(|| "BowongTextVideoAgent service not initialized".to_string())?
            .clone()
    };

    // 提交任务
    println!("=== 调用服务方法 ===");
    let result = service.hedra_submit_task(&params)
        .await
        .map_err(|e| {
            println!("=== 服务调用失败 ===");
            println!("错误信息: {}", e);
            format!("Failed to submit Hedra task: {}", e)
        })?;

    println!("=== 服务调用成功 ===");
    println!("响应: {:?}", result);

    // 如果任务提交成功，启动后台轮询
    if result.status && !result.data.is_empty() {
        let task_id = result.data.clone();

        // 获取必要的服务和仓库用于后台轮询
        let service_clone = service.clone();
        let event_bus = state.event_bus_manager.clone();
        let hedra_repo = {
            let repo_guard = state.hedra_lipsync_repository.lock()
                .map_err(|e| format!("获取仓库锁失败: {}", e))?;
            repo_guard.as_ref()
                .ok_or("Hedra repository not initialized")?
                .clone()
        };

        let task_id_clone = task_id.clone();
        let record_id_clone = record_id.clone();

        // 在后台启动异步轮询任务
        tokio::spawn(async move {
            if let Err(e) = poll_hedra_task_status(
                task_id_clone,
                record_id_clone,
                service_clone,
                event_bus,
                hedra_repo,
            ).await {
                eprintln!("Hedra 任务轮询失败: {}", e);
            }
        });

        println!("✅ 任务已提交并启动后台轮询: task_id={}, record_id={}", task_id, record_id);
    }

    Ok(result)
}

/// Hedra 查询任务状态
#[command]
pub async fn hedra_query_task_status(
    state: State<'_, AppState>,
    params: HedraTaskStatusParams,
) -> Result<TaskStatusResponse, String> {
    // 克隆服务以避免跨 await 点持有 MutexGuard
    let service = {
        let service_guard = state.get_bowong_service()
            .map_err(|e| format!("Failed to get BowongTextVideoAgent service: {}", e))?;

        service_guard.as_ref()
            .ok_or_else(|| "BowongTextVideoAgent service not initialized".to_string())?
            .clone()
    };

    service.hedra_query_task_status(&params)
        .await
        .map_err(|e| format!("Failed to query Hedra task status: {}", e))
}

/// 后台轮询 Hedra 任务状态
async fn poll_hedra_task_status(
    task_id: String,
    record_id: String,
    service: BowongTextVideoAgentService,
    event_bus: Arc<EventBusManager>,
    repository: Arc<HedraLipSyncRepository>,
) -> anyhow::Result<()> {
    use tokio::time::{sleep, Duration};
    use crate::data::models::hedra_lipsync_record::HedraLipSyncStatus;

    let max_polls = 360; // 30分钟 (5秒间隔 * 360次)
    let poll_interval = Duration::from_secs(5);

    for poll_count in 1..=max_polls {
        // 查询任务状态
        let status_params = HedraTaskStatusParams {
            task_id: task_id.clone(),
        };

        match service.hedra_query_task_status(&status_params).await {
            Ok(status_response) => {
                println!("任务 {} 状态: {} (轮询次数: {})", task_id, status_response.status, poll_count);

                // 映射状态
                let mapped_status = match status_response.status.as_str() {
                    "success" => "completed",
                    "running" => "processing",
                    "failed" => "failed",
                    "cancelled" => "cancelled",
                    "pending" | _ => "pending",
                };

                // 提取视频URL
                let video_url = if status_response.status == "success" {
                    println!("任务成功，提取视频URL，result: {:?}", status_response.result);
                    let url = status_response.result
                        .as_ref()
                        .and_then(|result| {
                            result.get("video_url")
                                .or_else(|| result.get("url"))
                                .or_else(|| result.get("video"))
                                .and_then(|v| v.as_str())
                                .map(|s| s.to_string())
                        });
                    println!("提取到的视频URL: {:?}", url);
                    url
                } else {
                    None
                };

                // 发送进度事件
                let _ = event_bus.publish_hedra_task_progress(
                    task_id.clone(),
                    record_id.clone(),
                    mapped_status.to_string(),
                    status_response.progress.map(|p| p as f64),
                    video_url.clone(),
                    status_response.error.clone(),
                ).await;

                // 更新数据库
                let db_status = match mapped_status {
                    "completed" => HedraLipSyncStatus::Completed,
                    "processing" => HedraLipSyncStatus::Processing,
                    "failed" => HedraLipSyncStatus::Failed,
                    "cancelled" => HedraLipSyncStatus::Cancelled,
                    _ => HedraLipSyncStatus::Pending,
                };

                let _ = repository.update_progress_and_result(
                    &record_id,
                    db_status,
                    status_response.progress.unwrap_or(0.0) as i32,
                    video_url,
                    status_response.error,
                );

                // 如果任务完成或失败，结束轮询
                if matches!(mapped_status, "completed" | "failed" | "cancelled") {
                    println!("任务 {} 已完成，状态: {}", task_id, mapped_status);
                    return Ok(());
                }
            }
            Err(e) => {
                eprintln!("查询任务 {} 状态失败: {}", task_id, e);

                // 如果连续查询失败次数过多，标记为失败
                if poll_count > 10 {
                    let _ = event_bus.publish_hedra_task_progress(
                        task_id.clone(),
                        record_id.clone(),
                        "failed".to_string(),
                        None,
                        None,
                        Some(format!("状态查询失败: {}", e)),
                    ).await;

                    let _ = repository.update_status_and_error(
                        &record_id,
                        HedraLipSyncStatus::Failed,
                        Some(format!("状态查询失败: {}", e)),
                    );

                    return Err(anyhow::anyhow!("连续查询失败: {}", e));
                }
            }
        }

        // 等待下次轮询
        sleep(poll_interval).await;
    }

    // 轮询超时
    let timeout_msg = "任务轮询超时";
    let _ = event_bus.publish_hedra_task_progress(
        task_id.clone(),
        record_id.clone(),
        "failed".to_string(),
        None,
        None,
        Some(timeout_msg.to_string()),
    ).await;

    let _ = repository.update_status_and_error(
        &record_id,
        HedraLipSyncStatus::Failed,
        Some(timeout_msg.to_string()),
    );

    Err(anyhow::anyhow!("任务轮询超时"))
}
