#!/usr/bin/env python3
"""
Test bulk operations performance specifically
"""

import time
from cutysoup import CutySoup

# Test HTML with lots of div elements
html = """
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
""" + "".join([f'<div class="test-{i}">Content {i}</div>' for i in range(100)]) + """
</body>
</html>
"""

def time_operation(func, iterations=10):
    times = []
    for _ in range(iterations):
        start = time.perf_counter()
        result = func()
        end = time.perf_counter()
        times.append((end - start) * 1000)
    return sum(times) / len(times), len(result) if hasattr(result, '__len__') else len(result) if result else 0

# Test CutySoup
soup = CutySoup(html)

print("🧪 Testing Bulk Operations Performance")
print("=" * 50)

# Test soup-level find_all (should use bulk operations)
soup_time, soup_count = time_operation(lambda: soup.find_all('div'))
print(f"soup.find_all('div'): {soup_time:.3f}ms ({soup_count} results)")

# Test root element find_all (should use bulk operations) 
root = soup.find('html')
if root:
    root_time, root_count = time_operation(lambda: root.find_all('div'))
    print(f"html.find_all('div'): {root_time:.3f}ms ({root_count} results)")

# Test body element find_all (should NOT use bulk operations)
body = soup.find('body') 
if body:
    body_time, body_count = time_operation(lambda: body.find_all('div'))
    print(f"body.find_all('div'): {body_time:.3f}ms ({body_count} results)")

# Test class search
class_time, class_count = time_operation(lambda: soup.find_all(class_='test-5'))
print(f"soup.find_all(class_='test-5'): {class_time:.3f}ms ({class_count} results)")

# Test direct bulk operations (debug)
if hasattr(soup._tree.get_root(), 'find_all_bulk'):
    print("\n🔧 Direct Bulk Operations Test:")
    root_node = soup._tree.get_root()
    
    def direct_bulk():
        return root_node.find_all_bulk('div', {})
    
    direct_time, direct_count = time_operation(direct_bulk)
    print(f"root.find_all_bulk('div'): {direct_time:.3f}ms ({direct_count} results)")
    
    def direct_class_bulk():
        return root_node.find_all_bulk('', {'class': 'test-5'})
    
    direct_class_time, direct_class_count = time_operation(direct_class_bulk)
    print(f"root.find_all_bulk(class='test-5'): {direct_class_time:.3f}ms ({direct_class_count} results)")
else:
    print("❌ Bulk operations not available")

print(f"\n📊 Performance Analysis:")
if 'soup_time' in locals() and 'direct_time' in locals():
    overhead = soup_time / direct_time if direct_time > 0 else float('inf')
    print(f"Python layer overhead: {overhead:.2f}x")
    print(f"Bulk ops efficiency: {direct_time / soup_time * 100:.1f}%" if soup_time > 0 else "N/A")