"""
CutySoup: High-performance HTML parsing library with BeautifulSoup4-compatible API

Sprint 3 - Modular Architecture
"""

# Core classes for backward compatibility
from .core import CutySoup, Tag, NavigableString

# Modular components (available for advanced usage)
from .css_selectors import CSSSelector, select_tags, select_one_tag
from .text_processing import TextProcessor
from .tree_manipulation import TreeManipulator
from .parser_config import ParserConfig, EncodingDetector, get_default_config, set_default_config, create_custom_config

# Sprint 7 - CSQL Query Language
from .csql import CSQLEngine, CSQLQuery
from .utils import (
    normalize_whitespace, is_tag_name_match, validate_html_content,
    validate_tag_name, validate_attribute_name, escape_html_attribute,
    unescape_html_attribute, build_tag_string
)
from .exceptions import (
    CutySoupException, ParseError, SelectorError, TreeManipulationError,
    NavigationError, EncodingError, ValidationError, ConfigurationError, SecurityError, CSQLError
)

# Sprint 3 - Enterprise Features
from .performance import (
    MemoryManager, PerformanceMonitor, ObjectPool, LRUCache,
    get_memory_manager, get_performance_monitor, timed, counted, cached
)
from .logging import (
    CutySoupLogger, LogLevel, LogFormat, LogContext, LogManager,
    get_logger, configure_logging, enable_debug_logging, disable_debug_logging,
    setup_enterprise_logging, logged_operation
)
from .security import (
    SecurityConfig, SecurityValidator, InputSanitizer, XXEProtection, RateLimiter,
    get_security_validator, configure_security, enable_strict_security,
    secure_operation, rate_limited
)

# Sprint 4 - Performance Revolution
from .performance_css import (
    HighPerformanceCSS, SelectorCompiler, select_fast, select_one_fast,
    get_css_engine, css_performance_monitor
)
from .lazy_results import (
    LazyResultSet, BatchFindResult, SmartObjectCache, 
    create_lazy_result_set, get_object_cache, get_lazy_monitor
)
from .memory_optimization import (
    StringInternPool, AdvancedMemoryPool, QueryOptimizationEngine, IndexManager,
    get_string_pool, get_optimization_engine, get_index_manager,
    intern_string, compare_interned, optimize_memory_globally
)
from .benchmarks import (
    PerformanceBenchmarker, RealWorldBenchmarks, RegressionTester,
    get_benchmarker, run_sprint4_benchmarks, quick_performance_test, benchmark_bs4_compatibility
)

# Backward compatibility - maintain original import structure
# Users can still do: from cutysoup import CutySoup, Tag, NavigableString
__version__ = "0.1.0"
__all__ = [
    # Core classes
    "CutySoup", "Tag", "NavigableString",
    
    # Modular components
    "CSSSelector", "select_tags", "select_one_tag",
    "TextProcessor", "TreeManipulator", 
    "ParserConfig", "EncodingDetector",
    
    # Configuration functions
    "get_default_config", "set_default_config", "create_custom_config",
    
    # Utility functions
    "normalize_whitespace", "is_tag_name_match", "validate_html_content",
    "validate_tag_name", "validate_attribute_name", "escape_html_attribute",
    "unescape_html_attribute", "build_tag_string",
    
    # Exceptions
    "CutySoupException", "ParseError", "SelectorError", "TreeManipulationError",
    "NavigationError", "EncodingError", "ValidationError", "ConfigurationError", "SecurityError", "CSQLError",
    
    # Sprint 7 - CSQL Query Language
    "CSQLEngine", "CSQLQuery",
    
    # Sprint 3 - Performance & Memory Management
    "MemoryManager", "PerformanceMonitor", "ObjectPool", "LRUCache",
    "get_memory_manager", "get_performance_monitor", "timed", "counted", "cached",
    
    # Logging
    "CutySoupLogger", "LogLevel", "LogFormat", "LogContext", "LogManager",
    "get_logger", "configure_logging", "enable_debug_logging", "disable_debug_logging",
    "setup_enterprise_logging", "logged_operation",
    
    # Security
    "SecurityConfig", "SecurityValidator", "InputSanitizer", "XXEProtection", "RateLimiter",
    "get_security_validator", "configure_security", "enable_strict_security",
    "secure_operation", "rate_limited",
    
    # Sprint 4 - Performance Revolution
    "HighPerformanceCSS", "SelectorCompiler", "select_fast", "select_one_fast",
    "get_css_engine", "css_performance_monitor",
    "LazyResultSet", "BatchFindResult", "SmartObjectCache", 
    "create_lazy_result_set", "get_object_cache", "get_lazy_monitor",
    "StringInternPool", "AdvancedMemoryPool", "QueryOptimizationEngine", "IndexManager",
    "get_string_pool", "get_optimization_engine", "get_index_manager",
    "intern_string", "compare_interned", "optimize_memory_globally",
    "PerformanceBenchmarker", "RealWorldBenchmarks", "RegressionTester",
    "get_benchmarker", "run_sprint4_benchmarks", "quick_performance_test",
    "benchmark_bs4_compatibility"
]

# Version information
__version_info__ = (0, 1, 0)
__author__ = "CutySoup Team"
__description__ = "High-performance HTML parsing library with BeautifulSoup4-compatible API"

# Configuration shortcuts for convenience
def configure_parser(**kwargs):
    """Configure the default parser settings."""
    set_default_config(**kwargs)

def enable_debug_mode():
    """Enable debug mode for detailed error reporting."""
    set_default_config(debug_mode=True)

def disable_debug_mode():
    """Disable debug mode."""
    set_default_config(debug_mode=False)

def set_strict_parsing(enabled: bool = True):
    """Enable or disable strict parsing mode."""
    set_default_config(strict_parsing=enabled)

def set_encoding(encoding: str):
    """Set default encoding for parsing."""
    set_default_config(encoding=encoding)

# Sprint 4 - Performance optimization shortcuts
def enable_turbo_mode():
    """Enable all Sprint 4 performance optimizations."""
    # Enable advanced CSS engine
    get_css_engine()
    
    # Warm up memory pools
    get_memory_manager()
    get_string_pool()
    get_index_manager()
    
    # Configure for maximum performance
    configure_parser(enable_caching=True, cache_size_limit=1000)
    
    print("🚀 CutySoup Turbo Mode enabled - maximum performance optimizations active!")

def benchmark_performance():
    """Run quick performance benchmark."""
    results = quick_performance_test()
    
    print("⚡ CutySoup Performance Test Results:")
    print(f"   Parsing: {results['parsing_ms']:.2f}ms")
    print(f"   CSS Selectors: {results['css_selector_ms']:.2f}ms") 
    print(f"   Find Operations: {results['find_all_ms']:.2f}ms")
    print(f"   Total: {results['total_ms']:.2f}ms")
    
    return results

def optimize_for_large_documents():
    """Optimize settings for large document processing."""
    configure_parser(
        max_tree_depth=5000,
        enable_caching=True,
        cache_size_limit=2000,
        memory_limit_mb=1000
    )
    
    # Pre-allocate larger pools
    memory_mgr = get_memory_manager()
    memory_mgr.create_pool("large_doc_pool", lambda: {}, max_size=2000)
    
    print("📄 Optimized for large document processing")

def optimize_for_batch_processing():
    """Optimize settings for batch processing many documents."""
    configure_parser(
        enable_caching=True,
        cache_size_limit=5000,
        memory_limit_mb=2000
    )
    
    # Enable string interning for repeated content
    get_string_pool()
    
    print("🔄 Optimized for batch processing")

def get_performance_summary():
    """Get comprehensive performance summary."""
    from .memory_optimization import get_memory_optimization_stats
    
    summary = {
        "sprint4_optimizations": True,
        "css_engine": get_css_engine().get_performance_stats(),
        "memory_optimization": get_memory_optimization_stats(),
        "lazy_operations": get_lazy_monitor().get_stats(),
        "performance_monitor": get_performance_monitor().get_all_stats()
    }
    
    return summary

# Maintain backward compatibility with old cutysoup.py
# Import original if modular version fails
try:
    # Verify modular imports work
    _test_import = CutySoup("")
except ImportError:
    # Fallback to original cutysoup.py if modular version fails
    try:
        from .cutysoup import CutySoup, Tag, NavigableString
    except ImportError:
        raise ImportError(
            "Neither modular nor original CutySoup implementation available. "
            "Please ensure the C++ extension is built properly."
        )
