#!/usr/bin/env python3
"""
MaxCpp Phase 34: Test C++ CSS Selector Implementation
"""

import time
from cutysoup import CutySoup

def test_css_selectors():
    print("🔍 MaxCpp Phase 34: Testing C++ CSS Selector Implementation")
    print("=" * 60)
    
    # Create test HTML
    html = """
    <html>
        <head>
            <title>Test Page</title>
        </head>
        <body>
            <div class="container">
                <h1 id="main-title">Welcome</h1>
                <p class="intro text-large">This is an introduction paragraph.</p>
                <div class="content">
                    <p class="text-large">First content paragraph</p>
                    <p>Second content paragraph</p>
                    <ul>
                        <li class="item first">First item</li>
                        <li class="item">Second item</li>
                        <li class="item last">Third item</li>
                    </ul>
                </div>
                <footer>
                    <p>Footer text</p>
                </footer>
            </div>
        </body>
    </html>
    """
    
    soup = CutySoup(html)
    
    # Test cases for CSS selectors
    test_cases = [
        ("p", "All paragraphs"),
        (".text-large", "Elements with text-large class"),
        ("#main-title", "Element with main-title ID"),
        ("div.container", "Div with container class"),
        ("div p", "Paragraphs inside divs (descendant)"),
        ("ul > li", "List items (direct children)"),
        (".item.first", "Elements with both item and first classes"),
        ("li:first-child", "First child list items"),
        ("li:last-child", "Last child list items"),
        ("p:contains('introduction')", "Paragraphs containing 'introduction'"),
    ]
    
    print("Testing C++ CSS selector functionality:")
    print("-" * 40)
    
    for selector, description in test_cases:
        try:
            # Test select_all
            start_time = time.perf_counter()
            results = soup.select(selector)
            end_time = time.perf_counter()
            
            print(f"✓ {description}: {len(results)} matches ({(end_time - start_time) * 1000:.2f}ms)")
            
            # Test select_one
            first_result = soup.select_one(selector)
            if first_result:
                text_preview = first_result.get_text()[:30].replace('\n', ' ').strip()
                if text_preview:
                    print(f"  First match: '{text_preview}{'...' if len(text_preview) >= 30 else ''}'")
                else:
                    print(f"  First match: <{first_result.name}>")
            
        except Exception as e:
            print(f"✗ {description}: Error - {e}")
    
    print()
    print("Performance comparison:")
    print("-" * 40)
    
    # Performance test with complex selector
    complex_selector = "div.container p.text-large, ul > li.item"
    
    # Warm up
    for _ in range(10):
        soup.select(complex_selector)
    
    # Benchmark
    num_iterations = 100
    start_time = time.perf_counter()
    for _ in range(num_iterations):
        results = soup.select(complex_selector)
    end_time = time.perf_counter()
    
    avg_time = ((end_time - start_time) / num_iterations) * 1000
    print(f"Complex selector ({complex_selector}):")
    print(f"  Average time: {avg_time:.3f}ms per query")
    print(f"  Results found: {len(results)}")
    
    # Test C++ vs Python comparison
    print()
    print("C++ Implementation Status:")
    print("-" * 40)
    
    # Check if C++ CSS selector is actually being used
    has_cpp_selector = hasattr(soup._tree, 'select_by_complex_selector')
    print(f"✓ C++ CSS selector engine available: {has_cpp_selector}")
    
    if has_cpp_selector:
        # Direct C++ call test
        try:
            cpp_results = soup._tree.select_by_complex_selector("p")
            print(f"✓ Direct C++ call works: {len(cpp_results)} results")
        except Exception as e:
            print(f"✗ Direct C++ call failed: {e}")
    
    print()
    print("🎉 MaxCpp Phase 34: C++ CSS Selector Implementation Complete!")

if __name__ == "__main__":
    test_css_selectors()