//! 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, LiveSpeechEvent, 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);

    // Subscribe to all events (recommended approach)
    let mut events = client.subscribe();
    tokio::spawn(async move {
        while let Ok(event) = events.recv().await {
            match event {
                LiveSpeechEvent::Connected(e) => {
                    println!("✅ Connected: {}", e.connection_id);
                }
                LiveSpeechEvent::SessionStarted(e) => {
                    println!("🎬 Session started: {}", e.session_id);
                }
                LiveSpeechEvent::Ready(_) => {
                    println!("✅ Ready for audio input");
                }
                LiveSpeechEvent::UserTranscript(e) => {
                    println!("👤 You said: \"{}\"", e.text);
                }
                LiveSpeechEvent::Response(e) => {
                    if e.is_final {
                        println!("🤖 AI: \"{}\"", e.text);
                    } else {
                        print!("\r🤖 AI: \"{}\"...", e.text);
                    }
                }
                LiveSpeechEvent::Audio(e) => {
                    println!("🔊 Received {} bytes of audio @ {}Hz", e.data.len(), e.sample_rate);
                    // In a real app, you would play this audio through speakers
                }
                LiveSpeechEvent::TurnComplete(_) => {
                    println!("🔄 Turn complete");
                }
                LiveSpeechEvent::SessionWarning(e) => {
                    println!("⚠️ Session warning: {}s remaining", e.remaining_seconds);
                }
                LiveSpeechEvent::SessionGoodbye(e) => {
                    println!("👋 Session ending soon: {}s remaining", e.remaining_seconds);
                }
                LiveSpeechEvent::Interrupted(_) => {
                    println!("⛔ AI response interrupted (barge-in)");
                }
                LiveSpeechEvent::ToolCall(e) => {
                    println!("🔧 Tool call: {} (id: {})", e.name, e.id);
                    println!("   Arguments: {:?}", e.args);
                    // In a real app, you would:
                    // 1. Execute the function
                    // 2. Call client.send_tool_response(&e.id, result).await
                }
                LiveSpeechEvent::UserIdUpdated(e) => {
                    println!("👤 User ID updated: {}, migrated {} messages", e.user_id, e.migrated_messages);
                }
                LiveSpeechEvent::Error(e) => {
                    eprintln!("❌ Error [{:?}]: {}", e.code, e.message);
                }
                LiveSpeechEvent::SessionEnded(e) => {
                    println!("🛑 Session ended: {}", e.session_id);
                }
                LiveSpeechEvent::Disconnected(e) => {
                    println!("🔌 Disconnected: {:?}", e.reason);
                }
                LiveSpeechEvent::Reconnecting(e) => {
                    println!("🔄 Reconnecting: attempt {}/{}", e.attempt, e.max_attempts);
                }
            }
        }
    });

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

    // 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(())
}
