//! Example demonstrating IndieWeb authorship discovery.
//!
//! Run with: cargo run -p example-authorship
//!
//! See: <https://indieweb.org/authorship-spec>

use indieweb::algorithms::authorship::resolve_author;
use indieweb::http::Client;
use indieweb::mf2::http::to_mf2_document;
use ::http::Request;
use microformats::types::{Class, KnownClass};
use url::Url;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = std::env::args().collect();
    let post_url_str = args.get(1).map(|s| s.as_str()).unwrap_or("https://example.com/post");

    let post_url = Url::parse(post_url_str)?;
    println!("Discovering author for: {post_url}");

    let client = indieweb::http::reqwest::Client::default();

    let req = Request::builder()
        .method("GET")
        .uri(post_url.to_string())
        .header("accept", "text/html")
        .body(Default::default())?;

    let resp = client.send_request(req).await?;
    let document = to_mf2_document(resp.map(|b| b.as_bytes().to_vec()), post_url.as_str())?;

    let entry = document
        .items
        .iter()
        .find(|item| item.r#type.contains(&Class::Known(KnownClass::Entry)));

    match entry {
        Some(entry) => {
            match resolve_author(&client, entry, &document, &post_url).await {
                Ok(author) => {
                    println!("Author discovered:");
                    println!("  Name: {}", author.name);
                    if let Some(url) = &author.url {
                        println!("  URL: {url}");
                    }
                    if let Some(photo) = &author.photo {
                        println!("  Photo: {photo}");
                    }
                }
                Err(e) => eprintln!("No author found: {e}"),
            }
        }
        None => eprintln!("No h-entry found on the page"),
    }

    Ok(())
}
