//! Steam-User Example - Friends List
//!
//! Demonstrates friend list operations: listing friends, getting personas, and
//! managing friends.
//!
//! # Usage
//! ```bash
//! REFRESH_TOKEN="your_refresh_token" cargo run --example friends_list
//! ```

use std::{collections::HashMap, time::Duration};

use steam_client::{EPersonaState, FriendsEvent, LogOnDetails, SteamClient, SteamEvent};
use steamid::SteamID;

#[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!("👥 Friends List Example\n");

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

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

    // Set online
    client.set_persona(EPersonaState::Online, None).await?;

    // Wait for friends list
    println!("\n📋 Waiting for friends list...");

    let mut friends_data: HashMap<SteamID, steam_client::FriendEntry> = HashMap::new();
    let mut received_list = false;
    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::Friends(FriendsEvent::FriendsList { friends, .. }))) => {
                println!("\n✅ Received friends list: {} friends\n", friends.len());
                for friend in &friends {
                    friends_data.insert(friend.steam_id, friend.clone());
                }
                received_list = true;
            }
            Ok(Some(SteamEvent::Friends(FriendsEvent::PersonaState(persona)))) => {
                if friends_data.contains_key(&persona.steam_id) {
                    // Got persona data for a friend
                    println!("   👤 {} ({}) - {:?}", persona.player_name, persona.steam_id.steam3(), persona.persona_state);
                }
            }
            Ok(Some(_)) => {}
            Ok(None) => {
                if received_list {
                    break;
                }
            }
            Err(_) => break,
        }
    }

    // Display summary
    println!("\n📊 Friends Summary:");
    println!("   Total friends: {}", friends_data.len());

    // Request Steam levels for some friends
    if !friends_data.is_empty() {
        let steam_ids: Vec<SteamID> = friends_data.keys().take(5).cloned().collect();

        println!("\n📈 Requesting Steam levels for first {} friends...", steam_ids.len());
        match client.get_steam_levels(steam_ids).await {
            Ok(_levels) => {
                // Response comes via events - for now just confirm request sent
                println!("   Request sent (response via events)");
            }
            Err(e) => {
                println!("   ❌ Failed to request levels: {:?}", e);
            }
        }
    }

    // Demonstrate persona request
    if !friends_data.is_empty() {
        let sample_ids: Vec<SteamID> = friends_data.keys().take(3).cloned().collect();
        println!("\n🔍 Requesting persona info for {} friends...", sample_ids.len());

        match client.get_personas(sample_ids).await {
            Ok(()) => {
                println!("   Request sent (response via PersonaState events)");
            }
            Err(e) => {
                println!("   ❌ Failed to request personas: {:?}", e);
            }
        }
    }

    // Wait briefly for responses
    tokio::time::sleep(Duration::from_secs(2)).await;

    // Drain any remaining events
    while let Some(event) = client.try_poll_event() {
        if let SteamEvent::Friends(FriendsEvent::PersonaState(persona)) = event {
            println!("   📬 {} - {:?}", persona.player_name, persona.persona_state);
        }
    }

    // Clean up
    client.log_off().await?;
    println!("\n👋 Done!");

    Ok(())
}
