//! Steam-User Example - Password Login
//!
//! Demonstrates the full password login flow including Steam Guard handling.
//!
//! # Usage
//! ```bash
//! cargo run --example password_login
//! ```
//!
//! The program will prompt for username, password, and Steam Guard code if
//! required.

use std::io::{self, Write};

use steam_client::{SteamClient, SteamError};

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

    // Collect credentials
    let account_name = prompt("Username: ")?;
    let password = prompt("Password: ")?;

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

    println!("\n🚀 Attempting login...");

    // Try to log in with password
    match client.log_on_with_password(&account_name, &password, None, None).await {
        Ok(response) => {
            println!("✅ Logged in successfully as {}", response.steam_id.steam3());
            print_login_success(&response);
        }
        Err(SteamError::SteamGuardRequired { guard_type, email_domain }) => {
            println!("\n🔐 Steam Guard required: {:?}", guard_type);
            if let Some(domain) = email_domain {
                println!("📧 Check your email at *****@{}", domain);
            }

            // Prompt for Steam Guard code
            let code = prompt("\nEnter Steam Guard code: ")?;

            // Submit the code
            match client.submit_steam_guard_code(&code).await {
                Ok(response) => {
                    println!("\n✅ Logged in successfully as {}", response.steam_id.steam3());
                    print_login_success(&response);
                }
                Err(e) => {
                    println!("❌ Failed to submit Steam Guard code: {:?}", e);
                    return Err(e.into());
                }
            }
        }
        Err(e) => {
            println!("❌ Login failed: {:?}", e);
            return Err(e.into());
        }
    }

    // Keep connection alive for a bit to receive events
    println!("\n📡 Receiving initial events...\n");

    for _ in 0..10 {
        match client.poll_event_timeout(std::time::Duration::from_secs(2)).await {
            Ok(Some(event)) => {
                println!("📬 Event: {:?}", event);
            }
            Ok(None) => break,
            Err(_) => break,
        }
    }

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

    Ok(())
}

fn prompt(message: &str) -> io::Result<String> {
    print!("{}", message);
    io::stdout().flush()?;
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    Ok(input.trim().to_string())
}

fn print_login_success(response: &steam_client::LogOnResponse) {
    println!("\n📋 Login Details:");
    println!("   Steam ID: {}", response.steam_id);
    println!("   Result: {:?}", response.eresult);
    if let Some(ref vanity) = response.vanity_url {
        println!("   Vanity URL: {}", vanity);
    }
    if let Some(ref ip) = response.public_ip {
        println!("   Public IP: {}", ip);
    }
}
