//! Simple generation example
//!
//! This example demonstrates:
//! 1. Submitting a generation request
//! 2. Examining the response structure
//! 3. Attempting to download if audio_url is available
//!
//! Run with:
//!   cargo run --example simple_generation

use std::fs;
use std::path::PathBuf;
use std::time::Duration;

use dotenvy::dotenv;
use reqwest::blocking::Client;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use sunocore::models::generation::{GenerateParams, GenerationResponse};
use sunocore::validation::env::{suno_api_key_unwrap, suno_base_url_unwrap};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let _ = dotenv();

    let base_url = suno_base_url_unwrap();
    let api_key = suno_api_key_unwrap().ok_or("SUNO_API_KEY not set")?;

    println!("=== Simple Suno Generation Example ===\n");

    // Create client with auth
    let mut headers = HeaderMap::new();
    headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
    headers.insert(
        AUTHORIZATION,
        HeaderValue::from_str(&format!("Bearer {}", api_key))?,
    );
    headers.insert("X-Api-Key", HeaderValue::from_str(&api_key)?);

    let client = Client::builder()
        .default_headers(headers)
        .timeout(Duration::from_secs(60))
        .build()?;

    // Create a simple generation request
    let params = GenerateParams::new("a cheerful acoustic guitar melody")
        .with_title("Happy Guitar")
        .with_instrumental(true);

    let url = format!("{}/api/generate/v2", base_url.trim_end_matches('/'));
    println!("Submitting to: {}", url);
    println!("Prompt: {}\n", params.prompt);

    let resp = client.post(&url).json(&params).send()?;
    let status = resp.status();
    let body = resp.text()?;

    println!("Response status: {}", status);

    if !status.is_success() {
        println!("Error: {}", &body[..body.len().min(500)]);
        return Err("Generation failed".into());
    }

    let gen_response: GenerationResponse = serde_json::from_str(&body)?;

    println!("\n✓ Generation Response:");
    println!("  Request ID: {}", gen_response.id);
    println!("  Status: {}", gen_response.status);
    println!("  Clips: {}\n", gen_response.clips.len());

    // Create output directory
    let output_dir = PathBuf::from("/Users/neil/suno/oxide/target/generated_songs");
    fs::create_dir_all(&output_dir)?;

    let mut downloaded_count = 0;

    for (idx, clip) in gen_response.clips.iter().enumerate() {
        println!("Clip {} ({})", idx + 1, clip.id);
        println!("  Status: {}", clip.status);
        println!("  Title: {:?}", clip.title);

        if let Some(ref audio_url) = clip.audio_url {
            if !audio_url.is_empty() {
                println!("  Audio URL: {}...", &audio_url[..audio_url.len().min(60)]);

                // Download the audio
                let download_client = Client::builder()
                    .timeout(Duration::from_secs(60))
                    .build()?;

                match download_client.get(audio_url).send() {
                    Ok(resp) if resp.status().is_success() => {
                        let bytes = resp.bytes()?;
                        let filename = format!(
                            "{:02}_{}.mp3",
                            idx + 1,
                            clip.title
                                .as_ref()
                                .map(|t| t.replace(" ", "_").replace("/", "_"))
                                .unwrap_or_else(|| clip.id.clone())
                        );
                        let output_path = output_dir.join(filename);

                        fs::write(&output_path, &bytes)?;
                        println!("  ✓ Downloaded {} bytes to {:?}\n", bytes.len(), output_path.file_name());
                        downloaded_count += 1;
                    }
                    Ok(resp) => {
                        println!("  ✗ Download failed: HTTP {}\n", resp.status());
                    }
                    Err(e) => {
                        println!("  ✗ Download error: {}\n", e);
                    }
                }
            } else {
                println!("  Audio URL: (empty - generation not complete yet)\n");
            }
        } else {
            println!("  Audio URL: (none - generation not complete yet)\n");
        }
    }

    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("✓ Complete!");
    println!("  Files downloaded: {}", downloaded_count);
    println!("  Output: {:?}", output_dir);
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

    Ok(())
}
