//! Steam-User Example - Anonymous Login
//!
//! Logs into Steam anonymously to fetch public information like app details.
//! No account credentials required!
//!
//! # Usage
//! ```bash
//! cargo run --example anonymous_login
//! ```

use std::time::Duration;

use steam_client::{AppsEvent, LogOnDetails, SteamClient, SteamEvent, SystemEvent};

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

    let mut client = SteamClient::new(Default::default());

    println!("🔓 Logging in anonymously...");

    // Log on anonymously (empty credentials)
    let response = client.log_on(LogOnDetails { anonymous: true, ..Default::default() }).await?;

    println!("✅ Logged in anonymously as {}", response.steam_id.steam3());
    println!("   (Anonymous accounts have SteamID type 'AnonUser')\n");

    // Wait for connection to stabilize
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Fetch some app info
    println!("📦 Requesting app information...\n");

    // Popular games to look up
    let app_ids = vec![
        440,     // Team Fortress 2
        730,     // CS:GO / CS2
        570,     // Dota 2
        1245620, // Elden Ring
    ];

    // Request product info - response comes via events
    client.get_product_info(app_ids.clone()).await?;

    // Wait for response events
    let start = std::time::Instant::now();
    while start.elapsed() < Duration::from_secs(10) {
        match client.poll_event_timeout(Duration::from_secs(1)).await {
            Ok(Some(SteamEvent::Apps(AppsEvent::ProductInfoResponse { apps, unknown_apps, .. }))) => {
                println!("📋 Received info for {} apps:\n", apps.len());
                for (app_id, app_data) in &apps {
                    println!("🎮 AppID: {}", app_id);
                    println!("   Change Number: {}", app_data.change_number);
                    if app_data.missing_token {
                        println!("   ⚠️ Token required for full info");
                    }
                    if let Some(ref info) = app_data.app_info {
                        // Try to extract name from VDF
                        if let Some(common) = info.get("appinfo").and_then(|i| i.get("common")) {
                            if let Some(name) = common.get_str("name") {
                                println!("   Name: {}", name);
                            }
                            if let Some(app_type) = common.get_str("type") {
                                println!("   Type: {}", app_type);
                            }
                        }
                    }
                    println!();
                }
                if !unknown_apps.is_empty() {
                    println!("❓ Unknown/unavailable apps: {:?}\n", unknown_apps);
                }
                break;
            }
            Ok(Some(SteamEvent::System(SystemEvent::Debug(msg)))) => {
                tracing::debug!("Debug: {}", msg);
            }
            Ok(Some(_)) => {}
            Ok(None) => {}
            Err(e) => {
                println!("❌ Error: {:?}", e);
                break;
            }
        }
    }

    // Also demonstrate getting player counts
    println!("📊 Requesting player counts...");
    for app_id in &app_ids[..2] {
        // Request player count - would need to wait for response
        if let Err(e) = client.get_player_count(*app_id).await {
            println!("   AppID {}: Error - {:?}", app_id, e);
        } else {
            println!("   AppID {}: Request sent (response via events)", app_id);
        }
    }

    println!();

    // Log off
    client.log_off().await?;
    println!("👋 Logged off");

    Ok(())
}
