use std::process;
use nwep::{Keypair, client::ClientBuilder, Url};

fn main() {
    let url = std::env::args().nth(1).unwrap_or_else(|| {
        eprintln!("usage: client <web://url/path>");
        process::exit(1);
    });

    nwep::init().unwrap_or_else(|e| {
        eprintln!("init: {e}");
        process::exit(1);
    });

    nwep::log::set_level(nwep::log::LogLevel::Warn);
    nwep::log::set_stderr(true);

    let parsed = Url::parse(&url).unwrap_or_else(|e| {
        eprintln!("parse url: {e}");
        process::exit(1);
    });
    let path = if parsed.path.is_empty() { "/".to_string() } else { parsed.path.clone() };

    let keypair = Keypair::generate().unwrap_or_else(|e| {
        eprintln!("keygen: {e}");
        process::exit(1);
    });

    let client = ClientBuilder::new()
        .connect(keypair, &url)
        .unwrap_or_else(|e| {
            eprintln!("connect: {e}");
            process::exit(1);
        });

    let resp = client.get(&path).unwrap_or_else(|e| {
        eprintln!("get: {e}");
        process::exit(1);
    });

    println!("{}", resp.status);
    println!("{}", String::from_utf8_lossy(&resp.body));

    client.close();
}
