// Copyright 2025 SkyReels SDK Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Basic usage example for SkyReels SDK
//!
//! This example demonstrates how to:
//! - Create a client
//! - Submit a text-to-video task
//! - Query task status

use std::task;

use skyreels::{AspectRatio, Mode, SkyReelsClient, TaskStatus};
use tracing::{info, warn};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load environment variables from .env file
    dotenv::dotenv().ok();

    // Initialize tracing for logging
    tracing_subscriber::fmt::init();

    // Get API key from environment variable
    let api_key = std::env::var("SKYREELS_API_KEY")
        .expect("SKYREELS_API_KEY environment variable not set");

    info!("Creating SkyReels client");
    let client = SkyReelsClient::new(&api_key);

    // Example 1: Basic text-to-video submission
    info!("Submitting basic text-to-video task");
    let request = client
        .text2video()
        .submit_request(
            "时间 画面描述 音效/配乐 0-5秒 微观世界：一只戴着迷你红色头盔的小蚂蚁，骑着一只跑得飞快的甲虫（马年创意变体），背上驮着一个比它身体还大的、写着“加急”的小红包，在花盆边缘狂奔。 快节奏的、类似《不可能的任务》的滑稽缩小版BGM。 6-10秒 跨障碍：甲虫“骏马”带着蚂蚁一跃而起，跳过一支横着的铅笔（像跨栏），越过一小滩水洼（像湖泊），镜头追身拍摄，清晰看到蚂蚁紧张的表情。 滑稽的跳跃音效，落地的水花声。 11-15秒 送达：甲虫精准刹停在一个巨大的“蚂蚁洞”门口（红包封面），门内伸出无数只小蚂蚁手，把红包接了进去。洞口出现一行字：“您的年货已送达，马到成功！”。 门铃“叮咚”声，蚂蚁们的欢呼声，收尾音乐。",
        )
        .duration(15)
        .sound(true)
        .build();

    // Note: This is a building example. In real usage, you would submit it:
    // let task_id = client.text2video().submit(request).await?;
    // info!("Task submitted with ID: {}", task_id);

    println!("Basic request created (not submitted)");

    // Example 2: Submit with custom parameters
    info!("Submitting text-to-video task with custom parameters");
    let _request = client
        .text2video()
        .submit_request(
            "A futuristic cityscape at night with flying cars and neon lights",
        )
        .duration(10)
        .aspect_ratio(AspectRatio::Portrait9x16)
        .sound(true)
        .mode(Mode::Std)
        .build();

    println!("Custom request created (not submitted)");

    // Example 3: Query task status
    // Note: Replace with an actual task ID from your submissions
    let task_id = "api-text2video-default-20260325-4fafe4d5-5a64-4bf7-9917-fa6534aaf782";
    let example_task_id =&task_id;
    match client.text2video().get_task(example_task_id).await {
        Ok(response) => {
            info!("Task status: {}", response.get_status());

            // 输出完整的 JSON 响应 (便于调试)
            if let Ok(json) = response.pretty_print() {
                info!("Full response JSON:\n{}", json);
            }

            match response.get_status() {
                TaskStatus::Success => {
                    if let Some(video_data) = response.get_video_data() {
                        info!("Video ready!");
                        info!("URL: {}", video_data.video_url);
                        info!("Duration: {} seconds", video_data.duration);
                        info!("Resolution: {}", video_data.resolution);
                    }
                }
                TaskStatus::Failed => {
                    warn!("Task failed: {}", response.msg);
                }
                TaskStatus::Submitted | TaskStatus::Pending | TaskStatus::Running => {
                    info!("Task is still being processed...");
                }
                _ => {}
            }
        }
        Err(e) => {
            warn!("Failed to query task status: {}", e);
        }
    }

    // Example 4: Wait for task completion
    // Note: This would work with an actual task ID
    // match client.text2video().wait_for_completion(task_id, 5, 120).await {
    //     Ok(response) => {
    //         info!("Task completed!");
    //         if let Some(video_data) = response.get_video_data() {
    //             info!("Video URL: {}", video_data.video_url);
    //         }
    //     }
    //     Err(e) => {
    //         warn!("Failed to wait for task completion: {}", e);
    //     }
    // }

    Ok(())
}
