use rs_url2json::JsonUrl;
use std::env;
use std::io::{self, Read};
use url::Url;

fn main() -> io::Result<()> {
    let url_str = get_url_from_args_or_stdin()?;
    let url = Url::parse(&url_str).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
    let json_url = JsonUrl::from(&url);
    let json = serde_json::to_string_pretty(&json_url).map_err(io::Error::other)?;
    println!("{}", json);
    Ok(())
}

fn get_url_from_args_or_stdin() -> io::Result<String> {
    for arg in env::args().skip(1) {
        if let Some(url) = arg.strip_prefix("--url=") {
            return Ok(url.to_string());
        }
    }

    let mut buffer = String::new();
    io::stdin().read_to_string(&mut buffer)?;
    Ok(buffer.trim().to_string())
}
