use text_video_agent_client::apis::configuration::Configuration;
use text_video_agent_client::apis::midjourney_api;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 创建支持 HTTPS 的客户端
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(30))
        .build()?;

    // 创建配置
    let config = Configuration {
        base_path: "https://bowongai-dev--text-video-agent-fastapi-app.modal.run".to_string(),
        user_agent: Some("text-video-agent-rust-client/1.0.6".to_string()),
        client,
        basic_auth: None,
        oauth_access_token: None,
        bearer_access_token: None,
        api_key: None,
    };

    println!("🎨 Midjourney 图像生成测试");
    println!("==========================");
    println!("API 地址: {}", config.base_path);
    println!();

    // 1. 健康检查
    println!("🔍 检查 Midjourney 服务状态...");
    match midjourney_api::health_check_api_mj_health_get(&config).await {
        Ok(response) => {
            println!("✅ Midjourney 服务正常: {}", response);
        }
        Err(e) => {
            println!("❌ Midjourney 服务异常: {:?}", e);
            return Ok(());
        }
    }
    println!();

    // 2. 测试提示词检查
    println!("📝 测试提示词预审...");
    let test_prompt = "a beautiful sunset over mountains, digital art, highly detailed";
    
    match midjourney_api::prompt_check_api_mj_prompt_check_get(&config, test_prompt).await {
        Ok(response) => {
            println!("✅ 提示词检查结果: {}", response);
        }
        Err(e) => {
            println!("❌ 提示词检查失败: {:?}", e);
        }
    }
    println!();

    // 3. 测试同步图像生成
    println!("🖼️ 测试同步图像生成...");
    let image_prompts = vec![
        "a cute cat sitting on a windowsill, watercolor style",
        "futuristic city skyline at night, cyberpunk style, neon lights",
        "peaceful zen garden with cherry blossoms, traditional Japanese art",
        "abstract geometric patterns in blue and gold, modern art",
    ];

    for (i, prompt) in image_prompts.iter().enumerate() {
        println!("🎯 生成图像 {}: {}", i + 1, prompt);
        
        match midjourney_api::generate_image_sync_api_mj_sync_image_post(
            &config,
            prompt,
            None,           // aspect_ratio
            None,           // model
            None,           // quality
            None,           // style
            None,           // chaos
            None,           // seed
            None,           // stylize
            None,           // weird
            None,           // tile
            None,           // no
            None,           // iw
            None,           // version
            None,           // uplight
            None,           // beta
            None,           // hd
            None,           // test
            None,           // testp
            None,           // creative
            None,           // fast
            None,           // relax
            None,           // stop
            None,           // video
            None,           // max_wait_time
            None,           // poll_interval
        ).await {
            Ok(response) => {
                println!("✅ 图像生成成功: {}", response);
            }
            Err(e) => {
                println!("❌ 图像生成失败: {:?}", e);
            }
        }
        println!();
        
        // 添加延迟避免请求过于频繁
        tokio::time::sleep(Duration::from_secs(3)).await;
    }

    // 4. 测试异步图像生成
    println!("⚡ 测试异步图像生成...");
    let async_prompt = "a majestic dragon flying over a medieval castle, fantasy art, epic scene";
    
    match midjourney_api::async_gen_image_api_mj_async_generate_image_post(
        &config,
        async_prompt,
        None, // img_file
    ).await {
        Ok(response) => {
            println!("✅ 异步任务提交成功: {}", response);
            
            // 尝试解析任务ID（假设响应中包含task_id字段）
            if let Some(task_id) = response.get("task_id").and_then(|v| v.as_str()) {
                println!("📋 任务ID: {}", task_id);
                
                // 轮询任务状态
                println!("⏳ 查询任务状态...");
                for attempt in 1..=5 {
                    tokio::time::sleep(Duration::from_secs(10)).await;
                    
                    match midjourney_api::async_query_status_api_mj_async_query_status_get(
                        &config,
                        task_id,
                    ).await {
                        Ok(status_response) => {
                            println!("📊 第{}次查询 - 任务状态: {}", attempt, status_response);
                            
                            // 检查任务是否完成（这里需要根据实际API响应格式调整）
                            if let Some(status) = status_response.get("status").and_then(|v| v.as_str()) {
                                if status == "completed" || status == "success" {
                                    println!("🎉 任务完成！");
                                    break;
                                } else if status == "failed" || status == "error" {
                                    println!("💥 任务失败！");
                                    break;
                                }
                            }
                        }
                        Err(e) => {
                            println!("❌ 查询状态失败: {:?}", e);
                        }
                    }
                }
            }
        }
        Err(e) => {
            println!("❌ 异步任务提交失败: {:?}", e);
        }
    }
    println!();

    println!("🎯 Midjourney 图像生成测试完成！");
    Ok(())
}
