//! Example: Handling rel=me Discovery
//!
//! This example demonstrates how to discover and work with `rel=me` links
//! on a page. These links indicate profiles or identities that belong to
//! the same person as the page.
//!
//! Common use cases:
//! - IndieAuth: Verify ownership of external profiles
//! - Identity verification: Confirm someone's social media accounts
//! - Profile discovery: Find all of someone's online presence
//!
//! # Usage
//! ```bash
//! cargo run --example rel_me_discovery
//! ```

use url::Url;

/// Get all rel=me URLs from a document
fn get_me_urls(document: &microformats::types::Document) -> Vec<Url> {
    document
        .rels
        .by_rels()
        .get("me")
        .cloned()
        .unwrap_or_default()
}

/// Check if a URL is a rel=me link on the page
fn is_me_link(document: &microformats::types::Document, url: &Url) -> bool {
    get_me_urls(document).contains(url)
}

/// Get detailed information about rel=me links
fn get_me_links_with_details(
    document: &microformats::types::Document,
) -> Vec<(Url, microformats::types::Relation)> {
    document
        .rels
        .items
        .iter()
        .filter(|(_, relation)| relation.rels.contains(&"me".to_string()))
        .map(|(url, relation)| (url.clone(), relation.clone()))
        .collect()
}

/// Categorize rel=me links by domain
fn categorize_me_links(
    document: &microformats::types::Document,
) -> std::collections::BTreeMap<String, Vec<Url>> {
    use std::collections::BTreeMap;

    let mut by_domain: BTreeMap<String, Vec<Url>> = BTreeMap::new();

    for url in get_me_urls(document) {
        if let Some(domain) = url.host_str() {
            by_domain.entry(domain.to_string()).or_default().push(url);
        }
    }

    by_domain
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let html = r#"
    <!DOCTYPE html>
    <html>
    <head>
        <!-- rel=me links in the head -->
        <link rel="me" href="https://github.com/janedoe">
        <link rel="me" href="https://twitter.com/janedoe">
        <link rel="me" href="https://mastodon.social/@janedoe">
        <link rel="author" href="https://example.com/about">
    </head>
    <body>
        <div class="h-card">
            <span class="p-name">Jane Doe</span>
            <a class="u-url" href="https://example.com/">Home</a>
        </div>

        <!-- rel=me can also appear in body links -->
        <footer>
            <p>Find me on:</p>
            <a rel="me" href="https://linkedin.com/in/janedoe">LinkedIn</a>
            <a rel="me" href="https://keybase.io/janedoe">Keybase</a>
        </footer>
    </body>
    </html>
    "#;

    let page_url: Url = "https://example.com/".parse()?;
    let document = microformats::from_html(html, &page_url)?;

    println!("=== rel=me Discovery ===\n");

    // Get all rel=me URLs
    let me_urls = get_me_urls(&document);
    println!("Found {} rel=me links:\n", me_urls.len());

    // Display with details
    let links_with_details = get_me_links_with_details(&document);
    for (url, relation) in &links_with_details {
        println!("URL: {}", url);
        if let Some(ref title) = relation.title {
            println!("  Title: {}", title);
        }
        if let Some(ref text) = relation.text {
            println!("  Text: {}", text);
        }
        println!();
    }

    // Categorize by domain
    println!("=== Links by Domain ===\n");
    let by_domain = categorize_me_links(&document);
    for (domain, urls) in &by_domain {
        println!("{}:", domain);
        for url in urls {
            println!("  - {}", url.path());
        }
        println!();
    }

    // Check specific URLs
    println!("=== URL Verification ===\n");

    let test_url: Url = "https://github.com/janedoe".parse()?;
    println!(
        "Is {} a rel=me link? {}",
        test_url,
        is_me_link(&document, &test_url)
    );

    let test_url: Url = "https://example.com/about".parse()?;
    println!(
        "Is {} a rel=me link? {}",
        test_url,
        is_me_link(&document, &test_url)
    );

    // Example: Use with IndieAuth
    println!("\n=== IndieAuth Example ===\n");
    println!("To verify a user's identity:");
    println!("1. Fetch their homepage (this page)");
    println!("2. Collect all rel=me URLs");
    println!("3. User attempts to authenticate with one of these providers");
    println!("4. Provider confirms the user's identity");
    println!("5. Check that the provider URL matches a rel=me link");
    println!();
    println!("Potential providers found: {}", me_urls.len());

    Ok(())
}
