webpage_quality_analyzer 1.0.2

High-performance webpage quality analyzer with 115 comprehensive metrics - Rust library with WASM, C++, and Python bindings
Documentation
//! Level 2 API - Builder Pattern Examples
//!
//! This example demonstrates the builder pattern for customizable analysis.
//! Perfect for applications that need fine-grained control over analysis parameters.

use webpage_quality_analyzer::{test_fixtures::*, Analyzer};

#[path = "common/macros.rs"]
mod macros;
use macros::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    print_section!("⚙️", "Level 2 API - Builder Pattern Examples");

    // Example 1: Basic builder usage
    print_section!("🏗️", "Example 1: Basic Builder");

    // Create analyzer with default configuration
    let analyzer: Analyzer = Analyzer::builder().build()?;

    let url = "https://httpbin.org/html";
    match analyzer.run(url, None).await {
        Ok(report) => {
            println!("✅ Basic builder analysis completed!");
            println!("   Score: {:.1}/100", report.score);
            println!(
                "   Active Profile: {}",
                analyzer
                    .get_active_profile_name()
                    .unwrap_or("unknown".to_string())
            );
        }
        Err(e) => println!("❌ Analysis failed: {}", e),
    }

    println!();

    // Example 2: Builder with profile selection
    print_section!("🎯", "Example 2: Profile Selection");

    let profiles = ["content_article", "news", "blog", "product"];

    for profile in &profiles {
        let analyzer: Analyzer = Analyzer::builder().with_profile_name(profile)?.build()?;

        match analyzer
            .run("https://news.example.com", Some(STRUCTURED_HTML))
            .await
        {
            Ok(report) => {
                print_score!(
                    format!("Profile '{}'", profile),
                    report.score,
                    report.verdict
                );
            }
            Err(e) => {
                print_error!(format!("Profile '{}'", profile), e);
            }
        }
    }

    println!();

    // Example 3: Advanced builder configuration
    print_section!("🔧", "Example 3: Advanced Configuration");

    let analyzer: Analyzer = Analyzer::builder()
        .with_profile_name("content_article")?
        .enable_linkcheck(true)
        .linkcheck_sample(50) // Check up to 50 links
        .enable_nlp(true) // Enable NLP features if available
        .add_report(true) // Include detailed report data
        .build()?;

    let complex_html = r##"
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Comprehensive Web Development Guide</title>
            <meta name="description" content="A complete guide to modern web development practices, tools, and techniques.">
            <meta name="author" content="Jane Developer">
        </head>
        <body>
            <header>
                <h1>The Complete Web Development Guide</h1>
                <nav>
                    <a href="#html">HTML</a>
                    <a href="#css">CSS</a>
                    <a href="#javascript">JavaScript</a>
                </nav>
            </header>
            
            <main>
                <section id="html">
                    <h2>HTML Fundamentals</h2>
                    <p>HTML forms the backbone of web content. Understanding semantic markup is crucial for accessibility and SEO.</p>
                    
                    <h3>Best Practices</h3>
                    <ul>
                        <li>Use semantic elements like article, section, and nav</li>
                        <li>Provide alt text for images</li>
                        <li>Structure content with proper headings</li>
                    </ul>
                    
                    <p>Here's an example of well-structured HTML:</p>
                    <img src="example.jpg" alt="HTML structure diagram showing semantic elements">
                </section>
                
                <section id="css">
                    <h2>CSS Styling</h2>
                    <p>CSS controls the visual presentation of your content. Modern CSS offers powerful layout tools like Flexbox and Grid.</p>
                    
                    <h3>Modern CSS Features</h3>
                    <p>CSS Grid and Flexbox have revolutionized web layout. These tools make responsive design more intuitive and maintainable.</p>
                </section>
                
                <section id="javascript">
                    <h2>JavaScript Programming</h2>
                    <p>JavaScript adds interactivity to web pages. Modern JavaScript includes many powerful features for building complex applications.</p>
                </section>
            </main>
            
            <footer>
                <p>© 2024 Web Development Guide. <a href="https://example.com/contact">Contact us</a></p>
            </footer>
        </body>
        </html>
    "##;

    match analyzer
        .run("https://webdev.example.com/guide", Some(complex_html))
        .await
    {
        Ok(report) => {
            println!("✅ Advanced analysis completed!");
            println!();
            println!("📊 Detailed Results:");
            println!(
                "   Overall Score: {:.1}/100 ({})",
                report.score, report.verdict
            );
            println!();

            // Content Analysis
            println!("📝 Content Analysis:");
            let content = &report.metrics.html_analysis.content;
            println!("   Word Count: {}", content.word_count);
            println!(
                "   Reading Time: {:.1} minutes",
                content.reading_time_minutes
            );
            println!(
                "   Unique Word Ratio: {:.1}%",
                content.unique_word_ratio * 100.0
            );
            if let Some(readability) = content.readability_fk {
                println!("   Readability Score: {:.1}", readability);
            }
            println!();

            // Structure Analysis
            println!("🏗️  Structure Analysis:");
            let structure = &report.metrics.html_analysis.structure;
            println!("   Headings Count: {}", structure.headings_count);
            println!("   Heading Depth: {}", structure.heading_depth);
            println!(
                "   Heading Order Score: {:.1}/100",
                structure.heading_order_score
            );
            println!("   Paragraph Count: {}", structure.paragraph_count);
            println!();

            // SEO Analysis
            println!("🔍 SEO Analysis:");
            let seo = &report.metrics.html_analysis.seo;
            println!("   Title Length: {} characters", seo.title_len);
            println!(
                "   Meta Description: {}",
                if seo.meta_desc_len.is_some() {
                    "Present"
                } else {
                    "Missing"
                }
            );
            println!(
                "   Viewport Tag: {}",
                if seo.viewport_tag_present {
                    "Present"
                } else {
                    "Missing"
                }
            );
            println!("   Open Graph Tags: {}", seo.og_tags);
            println!();

            // Link Analysis
            println!("🔗 Link Analysis:");
            let links = &report.metrics.html_analysis.links;
            println!("   Total Links: {}", links.total_links);
            println!("   Internal Links: {}", links.internal_links);
            println!("   External Links: {}", links.external_links);
            println!(
                "   Anchor Text Diversity: {:.1}%",
                links.anchor_text_diversity
            );
            println!();

            // Media Analysis
            println!("🖼️  Media Analysis:");
            let media = &report.metrics.html_analysis.media;
            println!("   Images Count: {}", media.images_count);
            println!("   Image Alt Coverage: {:.1}%", media.image_alt_coverage);
            println!("   Missing Alt Text: {}", media.missing_alt_text_count);
            println!();

            // Analysis Notes
            if !report.notes.is_empty() {
                println!("💡 Analysis Notes:");
                for note in &report.notes {
                    println!("{}", note);
                }
            }
        }
        Err(e) => println!("❌ Advanced analysis failed: {}", e),
    }

    println!();

    // Example 4: Multiple analyzer instances
    print_section!("🔄", "Example 4: Multiple Analyzer Instances");

    // Create different analyzers for different purposes
    // Blog analyzer
    let blog_analyzer: Analyzer = Analyzer::builder()
        .with_profile_name("blog")?
        .enable_nlp(true)
        .build()?;

    // Product page analyzer
    let product_analyzer: Analyzer = Analyzer::builder()
        .with_profile_name("product")?
        .enable_linkcheck(true)
        .linkcheck_sample(20)
        .build()?;

    // News analyzer
    let news_analyzer: Analyzer = Analyzer::builder()
        .with_profile_name("news")?
        .add_report(false) // Minimal report for speed
        .build()?;

    println!("Created specialized analyzers:");
    println!(
        "  📰 News Analyzer - Profile: {}",
        news_analyzer
            .get_active_profile_name()
            .unwrap_or("unknown".to_string())
    );
    println!(
        "  📝 Blog Analyzer - Profile: {}",
        blog_analyzer
            .get_active_profile_name()
            .unwrap_or("unknown".to_string())
    );
    println!(
        "  🛒 Product Analyzer - Profile: {}",
        product_analyzer
            .get_active_profile_name()
            .unwrap_or("unknown".to_string())
    );

    // Test with different content
    let blog_html = BLOG_HTML;
    let product_html = PRODUCT_HTML;
    let news_html = NEWS_HTML;

    if let Ok(blog_report) = blog_analyzer
        .run("https://blog.example.com", Some(blog_html))
        .await
    {
        println!("  📝 Blog Score: {:.1}/100", blog_report.score);
    }

    if let Ok(product_report) = product_analyzer
        .run("https://shop.example.com", Some(product_html))
        .await
    {
        println!("  🛒 Product Score: {:.1}/100", product_report.score);
    }

    if let Ok(news_report) = news_analyzer
        .run("https://news.example.com", Some(news_html))
        .await
    {
        println!("  📰 News Score: {:.1}/100", news_report.score);
    }

    print_completion!("Level 2 API examples completed!");

    print_takeaways!(
        "Use the builder pattern for customizable analysis",
        "Configure profiles, features, and options as needed",
        "Create specialized analyzer instances for different content types",
        "Access detailed metrics and metadata from reports",
        "Handle errors gracefully with proper Result handling"
    );

    Ok(())
}