use std::io::Write;

use clap::Parser;
use clap_stdin::FileOrStdin;
use microformats::jf2::IntoJf2;

#[derive(Parser, Debug)]
#[clap(version, about)]
struct Arguments {
    /// The URL to use as a base URL, if none can be found from the HTML.
    #[arg(short, long)]
    base_url: Option<url::Url>,

    /// The HTML to be parsed (can be piped via STDIN or be a path to a file).
    html: FileOrStdin,

    /// Present the result as JF2 instead.
    #[arg(short, long, default_value = "false")]
    jf2: bool,
}

fn main() -> eyre::Result<()> {
    let args = Arguments::parse();
    let html = args.html.contents()?;
    let parser = microformats::parse::Parser::from_html(html)?;

    let result = parser.into_document(args.base_url)?;

    let resulting_string = if args.jf2 {
        serde_json::to_string(&result.into_jf2()?)?
    } else {
        serde_json::to_string(&result)?
    };

    std::io::stdout().write_all(resulting_string.as_bytes())?;

    Ok(())
}
