#!/usr/bin/env python3
"""Test memory pool performance optimization."""

import time
from cutysoup import CutySoup

# Test HTML with many elements
test_html = """
<html>
<head><title>Test</title></head>
<body>
    <div class="container">
        <h1>Title</h1>
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
        <p>Paragraph 3</p>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
            <li>Item 5</li>
        </ul>
        <div class="content">
            <span>Span 1</span>
            <span>Span 2</span>
            <span>Span 3</span>
        </div>
    </div>
</body>
</html>
"""

def test_memory_pool_performance():
    """Test memory pool performance vs regular allocation."""
    print("Testing memory pool performance...")
    
    # Parse the HTML
    soup = CutySoup(test_html)
    
    # Test 1: Multiple find_all operations (creates many Tag objects)
    iterations = 1000
    
    start_time = time.perf_counter()
    for _ in range(iterations):
        # These operations create many Tag objects
        divs = soup.find_all('div')
        paragraphs = soup.find_all('p')
        list_items = soup.find_all('li')
        spans = soup.find_all('span')
        
        # Access properties to ensure objects are fully created
        for div in divs:
            _ = div.name
            _ = div.get('class', [])
        for p in paragraphs:
            _ = p.text
        for li in list_items:
            _ = li.text
        for span in spans:
            _ = span.text
    
    end_time = time.perf_counter()
    total_time = end_time - start_time
    
    print(f"Memory pool test completed:")
    print(f"- Iterations: {iterations}")
    print(f"- Total time: {total_time:.4f}s")
    print(f"- Average time per iteration: {(total_time/iterations)*1000:.2f}ms")
    
    # Test memory pool statistics
    from cutysoup.core import _tag_pool
    if _tag_pool:
        stats = _tag_pool.get_pool_stats()
        print(f"- Pool statistics:")
        print(f"  * Pool size: {stats['pool_size']}")
        print(f"  * Active tags: {stats['active_tags']}")
        print(f"  * Pool hits: {stats['hits']}")
        print(f"  * Pool misses: {stats['misses']}")
        print(f"  * Hit rate: {stats['hit_rate']:.1%}")

if __name__ == '__main__':
    test_memory_pool_performance()