#!/usr/bin/env python3
"""
Detailed benchmark comparison between CutySoup and BeautifulSoup4
"""

import time
import statistics
from cutysoup import CutySoup
from bs4 import BeautifulSoup

# Realistic test HTML (similar to critical test)
HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Performance Test Document</title>
    <style>
        .highlight { background-color: yellow; }
        .important { color: red; font-weight: bold; }
    </style>
</head>
<body>
    <header id="main-header" class="site-header">
        <h1>Performance Test Page</h1>
        <nav class="main-nav">
            <ul>
                <li><a href="#section1" class="nav-link">Section 1</a></li>
                <li><a href="#section2" class="nav-link">Section 2</a></li>
                <li><a href="#section3" class="nav-link">Section 3</a></li>
            </ul>
        </nav>
    </header>
    
    <main id="content">
        <section id="section1" class="content-section highlight">
            <h2>Test Section 1</h2>
            <p class="intro">This is an introduction paragraph with <strong>bold</strong> text.</p>
            <div class="data-container">
                <table class="data-table">
                    <thead>
                        <tr><th>Name</th><th>Value</th><th>Category</th></tr>
                    </thead>
                    <tbody>
                        <tr><td>Item 1</td><td data-value="100">$100.00</td><td class="category-a">Type A</td></tr>
                        <tr><td>Item 2</td><td data-value="250">$250.50</td><td class="category-b">Type B</td></tr>
                        <tr><td>Item 3</td><td data-value="75">$75.25</td><td class="category-a">Type A</td></tr>
                        <tr><td>Item 4</td><td data-value="300">$300.99</td><td class="category-c">Type C</td></tr>
                        <tr><td>Item 5</td><td data-value="150">$150.75</td><td class="category-b">Type B</td></tr>
                    </tbody>
                </table>
            </div>
        </section>
        
        <section id="section2" class="content-section">
            <h2>Test Section 2</h2>
            <div class="article-list">
                <article class="article-item important">
                    <h3>Article 1</h3>
                    <p class="excerpt">This is the first article excerpt...</p>
                    <div class="meta"><span class="date">2024-01-01</span><span class="author">Author 1</span></div>
                </article>
                <article class="article-item">
                    <h3>Article 2</h3>
                    <p class="excerpt">This is the second article excerpt...</p>
                    <div class="meta"><span class="date">2024-01-02</span><span class="author">Author 2</span></div>
                </article>
                <article class="article-item important">
                    <h3>Article 3</h3>
                    <p class="excerpt">This is the third article excerpt...</p>
                    <div class="meta"><span class="date">2024-01-03</span><span class="author">Author 3</span></div>
                </article>
            </div>
        </section>
    </main>
    
    <footer class="site-footer">
        <p>&copy; 2024 Performance Test. All rights reserved.</p>
        <div class="footer-links">
            <a href="#privacy" class="footer-link">Privacy</a>
            <a href="#terms" class="footer-link">Terms</a>
            <a href="#contact" class="footer-link">Contact</a>
        </div>
    </footer>
</body>
</html>
"""

def benchmark_operation(operation, name, iterations=10):
    """Benchmark a single operation."""
    times = []
    results = None
    
    for _ in range(iterations):
        start = time.perf_counter()
        results = operation()
        end = time.perf_counter()
        times.append((end - start) * 1000)  # Convert to ms
    
    mean_time = statistics.mean(times)
    result_count = len(results) if results else 0
    
    return {
        'name': name,
        'mean_ms': mean_time,
        'median_ms': statistics.median(times),
        'min_ms': min(times),
        'max_ms': max(times),
        'std_ms': statistics.stdev(times) if len(times) > 1 else 0,
        'result_count': result_count
    }

def run_benchmarks():
    """Run comprehensive benchmarks."""
    print("🚀 Comprehensive CutySoup vs BeautifulSoup4 Benchmark")
    print("=" * 60)
    
    # Parse documents
    cs_soup = CutySoup(HTML)
    bs4_soup = BeautifulSoup(HTML, 'html.parser')
    
    # Define test operations
    operations = [
        # Basic tag searches
        ('find_all_div', lambda soup: soup.find_all('div')),
        ('find_all_p', lambda soup: soup.find_all('p')),
        ('find_all_td', lambda soup: soup.find_all('td')),
        ('find_all_tr', lambda soup: soup.find_all('tr')),
        
        # Class searches
        ('find_all_article_item', lambda soup: soup.find_all(class_='article-item')),
        ('find_all_nav_link', lambda soup: soup.find_all(class_='nav-link')),
        ('find_all_category_a', lambda soup: soup.find_all(class_='category-a')),
        
        # Combined searches
        ('find_div_class_data', lambda soup: soup.find_all('div', class_='data-container')),
        ('find_p_class_excerpt', lambda soup: soup.find_all('p', class_='excerpt')),
        ('find_td_class_category', lambda soup: soup.find_all('td', class_='category-b')),
    ]
    
    cs_results = {}
    bs4_results = {}
    
    print("📊 CutySoup Results:")
    for op_name, op_func in operations:
        result = benchmark_operation(lambda: op_func(cs_soup), op_name)
        cs_results[op_name] = result
        print(f"  {op_name:25}: {result['mean_ms']:6.3f}ms ({result['result_count']:2d} results)")
    
    print("\n📊 BeautifulSoup4 Results:")
    for op_name, op_func in operations:
        result = benchmark_operation(lambda: op_func(bs4_soup), op_name)
        bs4_results[op_name] = result
        print(f"  {op_name:25}: {result['mean_ms']:6.3f}ms ({result['result_count']:2d} results)")
    
    print("\n📈 Performance Comparison:")
    print(f"{'Operation':<25} {'CS (ms)':<8} {'BS4 (ms)':<9} {'Ratio':<6} {'Status'}")
    print("-" * 60)
    
    faster_count = 0
    total_count = len(operations)
    
    for op_name in cs_results.keys():
        cs_time = cs_results[op_name]['mean_ms']
        bs4_time = bs4_results[op_name]['mean_ms']
        ratio = cs_time / bs4_time if bs4_time > 0 else float('inf')
        
        if ratio < 1.0:
            status = "✅ FASTER"
            faster_count += 1
        elif ratio < 1.2:
            status = "🟡 CLOSE"
        else:
            status = "❌ SLOWER"
            
        print(f"{op_name:<25} {cs_time:7.3f}  {bs4_time:8.3f}  {ratio:5.2f}x {status}")
    
    print(f"\n🎯 Summary:")
    print(f"  Operations faster than BS4: {faster_count}/{total_count} ({faster_count/total_count*100:.1f}%)")
    print(f"  Average speedup needed: {sum(cs_results[op]['mean_ms']/bs4_results[op]['mean_ms'] for op in cs_results)/len(cs_results):.2f}x")

if __name__ == "__main__":
    run_benchmarks()