/// Example: Upload data from an async reader using upload_from_reader_by_path.
use clap::Parser;
use futures::io::Cursor;
use megalib::SessionHandle;
use std::process;
use tracing_subscriber::{EnvFilter, fmt};

#[derive(Debug, Parser)]
#[command(name = "upload_reader")]
struct Args {
    #[arg(short = 'e', long)]
    email: String,
    #[arg(short = 'p', long)]
    password: String,
    #[arg(long)]
    proxy: Option<String>,
    remote_path: String,
}

fn init_tracing() {
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("off"));
    fmt().with_env_filter(filter).with_target(false).init();
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    init_tracing();
    let args = Args::parse();

    println!("Logging in...");
    let session = if let Some(proxy) = &args.proxy {
        SessionHandle::login_with_proxy(&args.email, &args.password, proxy).await?
    } else {
        SessionHandle::login(&args.email, &args.password).await?
    };
    let info = session.account_info().await?;
    println!("Logged in as: {}", info.email);

    println!("Refreshing filesystem...");
    session.refresh().await?;

    // Generate some data
    let data: Vec<u8> = (0..1024).map(|i| (i % 256) as u8).collect();
    let file_size = data.len() as u64;
    let file_name = "random_data.bin";

    // Create a Cursor that implements AsyncRead + AsyncSeek
    let cursor = Cursor::new(data);

    println!(
        "Uploading {} bytes as '{}' to {} using reader...",
        file_size, file_name, args.remote_path
    );

    match session
        .upload_from_reader_by_path(cursor, file_name, file_size, &args.remote_path)
        .await
    {
        Ok(node) => {
            println!("Upload complete!");
            println!("Created node: {} ({} bytes)", node.name, node.size);
        }
        Err(e) => {
            eprintln!("Error: {:?}", e);
            process::exit(1);
        }
    }

    Ok(())
}
