//! Steam-User Example - Licenses Dumper
//!
//! Dumps all owned licenses (games) for the logged-in account.
//!
//! # Usage
//! ```bash
//! REFRESH_TOKEN="your_refresh_token" cargo run --example licenses_dumper
//! ```

use std::time::Duration;

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

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

    let refresh_token = std::env::var("REFRESH_TOKEN").expect("Please set REFRESH_TOKEN environment variable");

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

    println!("📦 Licenses Dumper\n");

    // Log on
    let response = client.log_on(LogOnDetails { refresh_token: Some(refresh_token), ..Default::default() }).await?;

    println!("✅ Logged in as {}\n", response.steam_id.steam3());

    // Wait for licenses list
    println!("⏳ Waiting for licenses...\n");

    let start = std::time::Instant::now();
    while start.elapsed() < Duration::from_secs(15) {
        match client.poll_event_timeout(Duration::from_secs(1)).await {
            Ok(Some(SteamEvent::Apps(AppsEvent::LicenseList { licenses }))) => {
                println!("📋 Account owns {} license(s):\n", licenses.len());

                // Group by license type
                let mut free_licenses = vec![];
                let mut purchased = vec![];
                let mut other = vec![];

                for license in &licenses {
                    match license.license_type {
                        1 => free_licenses.push(license),
                        2..=4 => purchased.push(license),
                        _ => other.push(license),
                    }
                }

                // Print summary
                if !purchased.is_empty() {
                    println!("💰 Purchased ({}):", purchased.len());
                    for (i, license) in purchased.iter().enumerate().take(10) {
                        println!("   {}. Package {} (flags: {:#x})", i + 1, license.package_id, license.flags);
                    }
                    if purchased.len() > 10 {
                        println!("   ... and {} more", purchased.len() - 10);
                    }
                }

                if !free_licenses.is_empty() {
                    println!("\n🆓 Free ({}):", free_licenses.len());
                    for (i, license) in free_licenses.iter().enumerate().take(10) {
                        println!("   {}. Package {}", i + 1, license.package_id);
                    }
                    if free_licenses.len() > 10 {
                        println!("   ... and {} more", free_licenses.len() - 10);
                    }
                }

                if !other.is_empty() {
                    println!("\n📦 Other ({}):", other.len());
                    for (i, license) in other.iter().enumerate().take(5) {
                        println!("   {}. Package {} (type: {})", i + 1, license.package_id, license.license_type);
                    }
                    if other.len() > 5 {
                        println!("   ... and {} more", other.len() - 5);
                    }
                }

                println!();
                break;
            }
            Ok(Some(_)) => {}
            Ok(None) => {}
            Err(e) => {
                println!("❌ Error: {:?}", e);
                break;
            }
        }
    }

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

    Ok(())
}
