#!/usr/bin/env python3
"""Test advanced indexing features for large documents."""

import time
from cutysoup import CutySoup

# Test HTML with various elements
test_html = """
<html>
<head>
    <title>Advanced Indexing Test</title>
    <meta name="description" content="Testing advanced indexing">
    <meta name="keywords" content="test, indexing, performance">
</head>
<body>
    <div id="header" class="main-header">
        <h1>Header Title</h1>
        <nav class="navigation">
            <a href="/">Home</a>
            <a href="/about">About</a>
            <a href="/contact">Contact</a>
        </nav>
    </div>
    
    <div id="content" class="main-content">
        <article data-type="blog-post" data-author="John Doe">
            <h2>Article Title</h2>
            <p>First paragraph</p>
            <p>Second paragraph with <span class="highlight">highlighted text</span></p>
            <p>Third paragraph</p>
        </article>
        
        <aside data-type="sidebar" data-position="right">
            <h3>Sidebar Title</h3>
            <ul>
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
            </ul>
        </aside>
    </div>
    
    <footer id="footer" class="main-footer">
        <p>Copyright 2024</p>
        <div class="social-links">
            <a href="https://twitter.com" data-social="twitter">Twitter</a>
            <a href="https://facebook.com" data-social="facebook">Facebook</a>
        </div>
    </footer>
</body>
</html>
"""

def test_advanced_indexing():
    """Test the advanced indexing features."""
    print("Testing Advanced Indexing Features")
    print("=" * 50)
    
    # Parse the HTML
    soup = CutySoup(test_html)
    
    # Test if advanced indexing methods are available
    if hasattr(soup._tree, 'find_by_attribute'):
        print("✅ Advanced indexing methods available")
    else:
        print("❌ Advanced indexing methods not available")
        return
    
    # Test performance metrics
    try:
        build_time = soup._tree.get_index_build_time()
        element_count = soup._tree.get_indexed_node_count()
        print(f"📊 Index build time: {build_time:.6f} seconds")
        print(f"📊 Indexed elements: {element_count}")
    except Exception as e:
        print(f"⚠️  Performance metrics error: {e}")
    
    print("\n🔍 Advanced Search Tests:")
    
    # Test 1: Find by attribute
    print("\n1. Find by Attribute (data-type=blog-post):")
    try:
        start_time = time.perf_counter()
        results = soup._tree.find_by_attribute("data-type", "blog-post")
        end_time = time.perf_counter()
        
        print(f"   Found {len(results)} elements in {(end_time - start_time)*1000:.2f}ms")
        for result in results:
            print(f"   - <{result.get_name()}> with data-type='{result.get_attribute('data-type')}'")
    except Exception as e:
        print(f"   Error: {e}")
    
    # Test 2: Find by text content
    print("\n2. Find by Text Content ('Header Title'):")
    try:
        start_time = time.perf_counter()
        results = soup._tree.find_by_text_content("Header Title")
        end_time = time.perf_counter()
        
        print(f"   Found {len(results)} elements in {(end_time - start_time)*1000:.2f}ms")
        for result in results:
            print(f"   - <{result.get_name()}> containing: '{result.get_text()}'")
    except Exception as e:
        print(f"   Error: {e}")
    
    # Test 3: Get nth element
    print("\n3. Get Nth Element (index 5):")
    try:
        start_time = time.perf_counter()
        result = soup._tree.get_nth_element(5)
        end_time = time.perf_counter()
        
        if result:
            print(f"   Element found in {(end_time - start_time)*1000:.2f}ms")
            print(f"   - <{result.get_name()}> with id='{result.get_attribute('id')}' class='{result.get_attribute('class')}'")
        else:
            print("   No element at index 5")
    except Exception as e:
        print(f"   Error: {e}")
    
    # Test 4: Compare with regular find_all performance
    print("\n4. Performance Comparison:")
    try:
        # Using advanced indexing
        start_time = time.perf_counter()
        attr_results = soup._tree.find_by_attribute("class", "main-content")
        end_time = time.perf_counter()
        advanced_time = end_time - start_time
        
        # Using regular find_all
        start_time = time.perf_counter()
        regular_results = soup.find_all(attrs={'class': 'main-content'})
        end_time = time.perf_counter()
        regular_time = end_time - start_time
        
        print(f"   Advanced indexing: {advanced_time*1000:.2f}ms ({len(attr_results)} results)")
        print(f"   Regular find_all:  {regular_time*1000:.2f}ms ({len(regular_results)} results)")
        
        if advanced_time > 0:
            speedup = regular_time / advanced_time
            print(f"   Speedup: {speedup:.1f}x")
    except Exception as e:
        print(f"   Error: {e}")

def test_large_document_performance():
    """Test performance with a larger document."""
    print("\n" + "=" * 50)
    print("Large Document Performance Test")
    print("=" * 50)
    
    # Generate a larger HTML document
    large_html = "<html><body>"
    for i in range(1000):
        large_html += f"""
        <div id="item{i}" class="item-{i % 10}" data-index="{i}">
            <h3>Item {i}</h3>
            <p>Content for item {i}</p>
            <a href="/item/{i}" data-type="link">Link {i}</a>
        </div>
        """
    large_html += "</body></html>"
    
    print(f"📄 Generated HTML with ~{len(large_html)} characters")
    
    # Parse and test
    soup = CutySoup(large_html)
    
    try:
        build_time = soup._tree.get_index_build_time()
        element_count = soup._tree.get_indexed_node_count()
        print(f"📊 Index build time: {build_time:.6f} seconds")
        print(f"📊 Indexed elements: {element_count}")
        
        # Test various advanced searches
        print("\n🔍 Advanced Search Performance:")
        
        # Test attribute search
        start_time = time.perf_counter()
        results = soup._tree.find_by_attribute("data-type", "link")
        end_time = time.perf_counter()
        print(f"   Attribute search: {(end_time - start_time)*1000:.2f}ms ({len(results)} results)")
        
        # Test nth element access
        start_time = time.perf_counter()
        result = soup._tree.get_nth_element(500)
        end_time = time.perf_counter()
        print(f"   Nth element access: {(end_time - start_time)*1000:.2f}ms")
        
        # Test text content search
        start_time = time.perf_counter()
        results = soup._tree.find_by_text_content("Item 42")
        end_time = time.perf_counter()
        print(f"   Text content search: {(end_time - start_time)*1000:.2f}ms ({len(results)} results)")
        
    except Exception as e:
        print(f"   Error: {e}")

if __name__ == '__main__':
    test_advanced_indexing()
    test_large_document_performance()