// 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.

//! Complete workflow example for SkyReels SDK
//!
//! This example demonstrates a complete workflow from task submission
//! to downloading the generated video.

use skyreels::{AspectRatio, Error, Mode, SkyReelsClient};
use tracing::{error, info};

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

    tracing_subscriber::fmt::init();

    let api_key = std::env::var("SKYREELS_API_KEY")
        .expect("SKYREELS_API_KEY environment variable not set");

    let client = SkyReelsClient::new(&api_key);

    // Complete workflow: Submit -> Poll -> Download
    match complete_workflow(&client).await {
        Ok(video_url) => {
            info!("Workflow completed successfully!");
            info!("Final video URL: {}", video_url);
        }
        Err(e) => {
            error!("Workflow failed: {}", e);

            // Check if error is retryable
            if e.is_retryable() {
                info!("This error is retryable. You may want to try again later.");
            }
        }
    }

    Ok(())
}

async fn complete_workflow(client: &SkyReelsClient) -> Result<String, Error> {
    // Step 1: Submit a text-to-video task
    info!("Step 1: Submitting text-to-video task");
    let task_id = client
        .text2video()
        .submit_request(
            "A majestic eagle soaring through snow-capped mountains at sunrise, \
             cinematic shot with dramatic lighting",
        )
        .duration(8)
        .aspect_ratio(AspectRatio::Wide16x9)
        .sound(true)
        .mode(Mode::Std)
        .build();

    // Note: In actual usage, you would submit the request:
    // let task_id = client.text2video().submit(request).await?;

    // For demonstration, let's use a placeholder task ID
    let _task_id = "demo_task_id";

    info!("Task submitted (demo mode)");

    // Step 2: Poll for task completion
    info!("Step 2: Waiting for task completion");
    let response = client
        .text2video()
        .wait_for_completion(_task_id, 5, 120) // Poll every 5 seconds, max 120 attempts
        .await?;

    info!("Task completed with status: {}", response.get_status());

    // Step 3: Extract video URL
    if let Some(video_data) = response.get_video_data() {
        info!("Step 3: Video data retrieved");
        info!("Video URL: {}", video_data.video_url);
        info!("Duration: {} seconds", video_data.duration);
        info!("Resolution: {}", video_data.resolution);

        // Step 4: Optionally download the video
        // download_video(&video_data.video_url, "output.mp4").await?;

        Ok(video_data.video_url.clone())
    } else {
        Err(Error::QueryFailed(
            "Task completed but no video data available".to_string(),
        ))
    }
}

// Optional: Download the video from URL
// async fn download_video(url: &str, output_path: &str) -> Result<(), Error> {
//     info!("Downloading video from {} to {}", url, output_path);
//
//     let response = reqwest::get(url).await?;
//     let bytes = response.bytes().await?;
//
//     tokio::fs::write(output_path, bytes).await?;
//
//     info!("Video downloaded successfully to {}", output_path);
//     Ok(())
// }
