//! LiveSpeech SDK - Basic Usage Example (Rust)
//!
//! This example demonstrates how to use the LiveSpeech SDK to create
//! a real-time speech-to-speech AI conversation using streaming audio.
//!
//! Run with: cargo run --example basic_usage

use livespeech_sdk::{Config, LiveSpeechClient, Region, SessionConfig};
use std::env;
use tokio::signal;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize logging
    tracing_subscriber::fmt::init();

    // Get API key from environment
    let api_key = env::var("LIVESPEECH_API_KEY")
        .unwrap_or_else(|_| "your-api-key".to_string());

    println!("=== LiveSpeech SDK Rust Example ===\n");
    println!("Region: {} ({})", Region::ApNortheast2, Region::ApNortheast2.endpoint());

    // Create client configuration using region
    let config = Config::builder()
        .region(Region::ApNortheast2)  // Asia Pacific (Seoul)
        .api_key(api_key)
        .debug(true)
        .auto_reconnect(true)
        .max_reconnect_attempts(5)
        .build()?;

    // Create client
    let client = LiveSpeechClient::new(config);

    // Set up event handlers
    client
        .on_transcript(|text, is_final| {
            if is_final {
                println!("📝 You said: \"{}\"", text);
            } else {
                print!("\r📝 Transcribing: \"{}\"...", text);
            }
        })
        .await;

    client
        .on_response(|text, is_final| {
            if is_final {
                println!("\n🤖 AI: \"{}\"", text);
            } else {
                print!("\r🤖 AI: \"{}\"...", text);
            }
        })
        .await;

    client
        .on_audio(|audio_data| {
            println!("🔊 Received {} bytes of audio", audio_data.len());
            // In a real app, you would play this audio through speakers
        })
        .await;

    client
        .on_error(|event| {
            eprintln!("❌ Error [{:?}]: {}", event.code, event.message);
        })
        .await;

    // Connect to the server
    println!("\nConnecting to LiveSpeech server...");
    client.connect().await?;
    println!("✅ Connected!");

    // Start a session with system prompt
    let session_config = SessionConfig::new(
        "You are a friendly and helpful AI assistant. \
         Keep your responses concise but informative. \
         Be conversational and engaging."
    );

    let session_id = client.start_session(Some(session_config)).await?;
    println!("🎬 Session started: {}", session_id);

    // Start audio streaming
    client.audio_start().await?;
    println!("🎙️ Audio streaming started");

    // Example: Send audio chunks (in a real app, this would come from a microphone)
    println!("\nIn a real app:");
    println!("1. Capture audio from microphone");
    println!("2. Convert to PCM16 format at 16kHz");
    println!("3. Call client.send_audio_chunk(&audio_data).await");
    println!("4. Call client.audio_end().await when done\n");

    // Simulate sending audio chunks (silence for demo)
    let chunk_size = 3200; // 100ms at 16kHz mono PCM16
    let dummy_chunk = vec![0u8; chunk_size];

    // Send a few chunks of silence
    for _ in 0..3 {
        client.send_audio_chunk(&dummy_chunk).await?;
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    }

    // End audio streaming
    client.audio_end().await?;
    println!("🔇 Audio streaming ended");

    // Keep the connection alive for demo purposes
    println!("\nPress Ctrl+C to exit...\n");

    // Wait for shutdown signal
    signal::ctrl_c().await?;

    // Graceful shutdown
    println!("\nShutting down...");
    client.end_session().await?;
    client.disconnect().await;

    Ok(())
}
