use mailcore::dns::discover_mail_server;
use mailcore::imap::ImapClient;
use std::io::{self, Write};

#[tokio::main]
async fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() < 2 {
        eprintln!("Usage: test_imap <email>");
        std::process::exit(1);
    }
    let email = &args[1];

    println!("Discovering server for: {}", email);
    let config = match discover_mail_server(email).await {
        Ok(c) => {
            println!("✓ IMAP: {}:{}", c.imap_host, c.imap_port);
            c
        }
        Err(e) => {
            eprintln!("✗ DNS Error: {}", e);
            return;
        }
    };

    print!("Password for {}: ", email);
    io::stdout().flush().unwrap();
    let mut password = String::new();
    io::stdin().read_line(&mut password).unwrap();
    let password = password.trim();

    let mut client = ImapClient::new(config, email.to_string());

    println!("Connecting...");
    match client.connect(password).await {
        Ok(_) => {
            println!("✓ Connected and authenticated successfully!");

            println!("Listing folders...");
            match client.list_folders(true).await {
                Ok(folders) => {
                    println!("\nFolders:");
                    for folder in folders {
                        println!("  - {} ({:?})", folder.name, folder.folder_type);
                    }
                }
                Err(e) => eprintln!("✗ Failed to list folders: {}", e),
            }
        }
        Err(e) => eprintln!("✗ Connection Error: {}", e),
    }
}
