#!/usr/bin/env python3
"""
Simple test to validate parallel functionality works
"""

import sys
import os
import time

# Add the package directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__)))

try:
    from cutysoup import CutySoup
    CUTYSOUP_AVAILABLE = True
except ImportError as e:
    print(f"[ERROR] CutySoup not available: {e}")
    CUTYSOUP_AVAILABLE = False

if not CUTYSOUP_AVAILABLE:
    print("Please build CutySoup first: uv sync")
    sys.exit(1)


def test_basic_parallel():
    """Test basic parallel functionality."""
    print("Testing Basic Parallel Functionality")
    print("=" * 50)
    
    # Create a simple test document
    html = """
    <html>
        <body>
            <div class="container">
                <p class="text">Paragraph 1</p>
                <p class="text">Paragraph 2</p>
                <article id="main">Main article</article>
                <div class="content">Content div</div>
                <p>Another paragraph</p>
            </div>
        </body>
    </html>
    """
    
    soup = CutySoup(html)
    root_node = soup._tree.get_root()
    
    print("Testing parallel methods availability...")
    
    # Test if parallel methods exist
    if hasattr(root_node, 'find_all_parallel'):
        print("[OK] find_all_parallel method available")
    else:
        print("[ERROR] find_all_parallel method not available")
        return False
        
    if hasattr(root_node, 'find_parallel'):
        print("[OK] find_parallel method available")
    else:
        print("[ERROR] find_parallel method not available")
        return False
    
    print("\nTesting basic operations...")
    
    # Test basic find_all_parallel
    try:
        parallel_paragraphs = root_node.find_all_parallel('p')
        sequential_paragraphs = root_node.find_all('p')
        
        print(f"Parallel find_all('p'): {len(parallel_paragraphs)} results")
        print(f"Sequential find_all('p'): {len(sequential_paragraphs)} results")
        
        if len(parallel_paragraphs) == len(sequential_paragraphs):
            print("[OK] find_all_parallel returns same count as sequential")
        else:
            print("[ERROR] find_all_parallel count mismatch")
            return False
            
    except Exception as e:
        print(f"[ERROR] find_all_parallel failed: {e}")
        return False
    
    # Test find_parallel (single result)
    try:
        parallel_article = root_node.find_parallel('article')
        sequential_article = root_node.find('article')
        
        parallel_found = parallel_article is not None
        sequential_found = sequential_article is not None
        
        print(f"Parallel find('article'): {'Found' if parallel_found else 'Not found'}")
        print(f"Sequential find('article'): {'Found' if sequential_found else 'Not found'}")
        
        if parallel_found == sequential_found:
            print("[OK] find_parallel returns same result as sequential")
        else:
            print("[ERROR] find_parallel result mismatch")
            return False
            
    except Exception as e:
        print(f"[ERROR] find_parallel failed: {e}")
        return False
    
    # Test class-based search
    try:
        parallel_text = root_node.find_all_parallel('', {'class': 'text'})
        sequential_text = root_node.find_all('', {'class': 'text'})
        
        print(f"Parallel find class 'text': {len(parallel_text)} results")
        print(f"Sequential find class 'text': {len(sequential_text)} results")
        
        if len(parallel_text) == len(sequential_text):
            print("[OK] Class-based search works correctly")
        else:
            print("[ERROR] Class-based search mismatch")
            return False
            
    except Exception as e:
        print(f"[ERROR] Class-based search failed: {e}")
        return False
    
    # Test ID-based search
    try:
        parallel_main = root_node.find_parallel('', {'id': 'main'})
        sequential_main = root_node.find('', {'id': 'main'})
        
        parallel_found = parallel_main is not None
        sequential_found = sequential_main is not None
        
        print(f"Parallel find ID 'main': {'Found' if parallel_found else 'Not found'}")
        print(f"Sequential find ID 'main': {'Found' if sequential_found else 'Not found'}")
        
        if parallel_found == sequential_found:
            print("[OK] ID-based search works correctly")
        else:
            print("[ERROR] ID-based search mismatch")
            return False
            
    except Exception as e:
        print(f"[ERROR] ID-based search failed: {e}")
        return False
    
    print("\n[SUCCESS] All basic parallel tests passed!")
    return True


def test_simple_performance():
    """Test simple performance comparison."""
    print("\nTesting Simple Performance Comparison")
    print("=" * 50)
    
    # Create a document with more elements
    html_parts = ['<html><body>']
    for i in range(100):
        html_parts.append(f'<div class="item" id="item{i}"><p>Item {i}</p></div>')
    html_parts.append('</body></html>')
    
    html = ''.join(html_parts)
    soup = CutySoup(html)
    root_node = soup._tree.get_root()
    
    print(f"Test document: {len(html)} characters, ~100 elements")
    
    # Time sequential operation
    start_time = time.perf_counter()
    sequential_divs = root_node.find_all('div')
    sequential_time = (time.perf_counter() - start_time) * 1000
    
    # Time parallel operation
    start_time = time.perf_counter()
    parallel_divs = root_node.find_all_parallel('div')
    parallel_time = (time.perf_counter() - start_time) * 1000
    
    print(f"Sequential time: {sequential_time:.2f}ms ({len(sequential_divs)} results)")
    print(f"Parallel time:   {parallel_time:.2f}ms ({len(parallel_divs)} results)")
    
    if len(sequential_divs) == len(parallel_divs):
        print("[OK] Result counts match")
        
        if parallel_time < sequential_time:
            speedup = sequential_time / parallel_time
            print(f"[SPEEDUP] Parallel is {speedup:.2f}x faster")
        else:
            slowdown = parallel_time / sequential_time
            print(f"[INFO] Parallel is {slowdown:.2f}x slower (expected for small documents)")
    else:
        print("[ERROR] Result count mismatch")
        return False
    
    return True


def main():
    """Main test function."""
    print("CutySoup Simple Parallel Test")
    print("=" * 50)
    
    success = True
    
    try:
        success &= test_basic_parallel()
        success &= test_simple_performance()
        
        if success:
            print("\n[COMPLETE] All tests passed successfully!")
            print("Parallel processing implementation is working correctly.")
        else:
            print("\n[FAILED] Some tests failed.")
            
    except Exception as e:
        print(f"\n[ERROR] Test failed with exception: {e}")
        import traceback
        traceback.print_exc()
        success = False
    
    return success


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)