# Create performance test suite: tests/test_performance.py
import pytest
import pandas as pd
import numpy as np
from memory_profiler import profile
import gc

class TestPerformanceHardening:
    @pytest.fixture
    def mixed_script_data(self):
        """Generate 1M row mixed-script dataset."""
        np.random.seed(42)
        
        # Mix of scripts
        latin_names = ["Smith", "Johnson", "Williams", "Brown", "Jones"]
        cyrillic_names = ["Иванов", "Петров", "Сидоров", "Васильев", "Михайлов"]
        arabic_names = ["محمد", "أحمد", "علي", "حسن", "عبدالله"]
        cjk_names = ["王", "李", "张", "刘", "陈"]
        
        n = 1_000_000
        data = {
            "id": range(n),
            "name": np.random.choice(
                latin_names + cyrillic_names + arabic_names + cjk_names, 
                size=n
            ),
            "company": np.random.choice(
                ["ABC Corp", "XYZ Ltd", "テスト会社", "مؤسسة"], 
                size=n
            ),
            "email": [f"user{i}@example.com" for i in range(n)]
        }
        
        return pd.DataFrame(data)
    
    @profile
    def test_memory_usage(self, mixed_script_data):
        """Test memory usage stays within bounds."""
        from fmatch.core.engine import determine_optimal_blocking_strategy
        
        # Force garbage collection
        gc.collect()
        
        # Run blocking analysis
        result = determine_optimal_blocking_strategy(
            mixed_script_data.head(100_000),
            mappings=[{"source": "company", "ref": "company"}],
            mode="duplicate"
        )
        
        # Memory should not exceed 2GB for 100k rows
        assert result is not None
        
    def test_regex_performance(self):
        """Test optimized regex performance."""
        from fmatch.core.engine import _detect_script
        
        # Pre-compiled regex should be fast
        test_strings = ["Hello", "Привет", "مرحبا", "你好"] * 10000
        
        import time
        start = time.time()
        for s in test_strings:
            _detect_script(s)
        elapsed = time.time() - start
        
        # Should process 40k strings in under 1 second
        assert elapsed < 1.0