"""
Pattern Management Server Module
Specialized server for regex pattern management and matching tools.
"""

from typing import Dict, List, Optional
from fastmcp import FastMCP

# Import pattern-related modules with flexible import handling
try:
    # Try relative imports first (when run as module)
    from ..context_logic import pattern_management, regex_analysis
except ImportError:
    # Fall back to absolute imports (when run from parent directory)
    from context_logic import pattern_management, regex_analysis


def create_patterns_server() -> FastMCP:
    """
    Create a specialized server for pattern management and regex tools.
    
    Returns:
        FastMCP server instance with pattern tools
    """
    server = FastMCP(
        name="Storm Logger Pattern Management Server",
        instructions="""
        This server provides comprehensive pattern management tools to help you 
        ESCAPE REGEX HELL and create maintainable pattern matching systems.
        """,
    )
    
    @server.tool(tags={"public", "stable"})
    def avoid_regex_hell_create_pattern_matcher(
        name: str,
        description: str,
        patterns: Dict[str, tuple],
        priority: str = "MEDIUM"
    ) -> str:
        """
        Create clean, maintainable pattern matchers instead of complex regex patterns.
        This tool helps you AVOID REGEX HELL by generating proper PatternMatcher classes.
        
        Args:
            name: Name of the matcher class (e.g., "PaymentCardMatcher")
            description: Clear description of what patterns this matcher handles
            patterns: Simple dict mapping pattern names to (regex, replacement) tuples
            priority: Priority level (CRITICAL, HIGH, MEDIUM, LOW)
            
        Returns:
            Complete Python class code using Storm Logger's pattern matching system
        """
        return pattern_management.create_pattern_matcher(
            name, description, patterns, priority
        )
    
    @server.tool(tags={"public", "stable"})
    def escape_regex_hell_convert_to_pattern(
        regex: str,
        replacement: str,
        pattern_name: str
    ) -> str:
        """
        Convert complex regex patterns into Storm Logger's clean pattern system.
        ESCAPE REGEX HELL by transforming unreadable regex into maintainable patterns.
        
        Args:
            regex: The complex regex pattern you want to escape from
            replacement: What to replace matches with (e.g., '[REDACTED]')
            pattern_name: Descriptive name for this pattern (e.g., 'credit_card')
            
        Returns:
            Clean pattern definition ready to use in a PatternMatcher class
        """
        return pattern_management.convert_regex_to_pattern(
            regex, replacement, pattern_name
        )
    
    @server.tool(tags={"public", "stable"})
    def debug_regex_hell_pattern_conflicts(
        patterns: List[str],
        test_data: str
    ) -> str:
        """
        Analyze and debug pattern conflicts to prevent regex hell overlap issues.
        Shows exactly why your patterns are creating a mess and how to fix them.
        
        Args:
            patterns: List of regex patterns that might be conflicting
            test_data: Sample text to test patterns against
            
        Returns:
            Detailed analysis showing conflicts, overlaps, and recommendations
        """
        return regex_analysis.debug_pattern_conflicts(patterns, test_data)
    
    @server.tool(tags={"public", "stable"})
    def no_more_regex_hell_pattern_library(
        category: str
    ) -> str:
        """
        Get pre-built pattern matchers for common use cases - NO MORE REGEX HELL!
        Access Storm Logger's pattern libraries instead of writing complex regex.
        
        Args:
            category: Type of patterns needed:
                - "financial": Credit cards, IBANs, routing numbers, etc.
                - "medical": Patient IDs, medical record numbers, etc.
                - "security": API keys, tokens, credentials, etc.
                - "cloud": AWS keys, Azure credentials, GCP tokens, etc.
                
        Returns:
            Complete PatternMatcher class code ready to use
        """
        return pattern_management.get_pattern_library(category)
    
    @server.tool(tags={"public", "experimental"})
    def optimize_pattern_performance(
        pattern_class: str,
        test_cases: List[str] = None
    ) -> str:
        """
        Optimize pattern matching performance for high-volume scenarios
        
        Args:
            pattern_class: Python code of the pattern class to optimize
            test_cases: List of test cases to benchmark against
            
        Returns:
            JSON string with optimization suggestions and performance improvements
        """
        return pattern_management.optimize_pattern_performance(
            pattern_class, test_cases or []
        )
    
    @server.tool(tags={"public", "stable"})
    def validate_pattern_security(
        patterns: Dict[str, str],
        security_level: str = "enterprise"
    ) -> str:
        """
        Validate patterns for security vulnerabilities and compliance
        
        Args:
            patterns: Dictionary of pattern names to regex patterns
            security_level: Security level (basic, standard, enterprise)
            
        Returns:
            JSON string with security analysis and recommendations
        """
        return pattern_management.validate_pattern_security(
            patterns, security_level
        )
    
    # Resources
    @server.resource("storm-logger://patterns/library")
    def get_pattern_library_overview() -> str:
        """
        Get overview of available pattern libraries.
        
        Returns:
            JSON string with pattern library information
        """
        return """
        {
            "pattern_libraries": {
                "financial": {
                    "description": "Financial data patterns (credit cards, IBANs, etc.)",
                    "patterns": {
                        "credit_card": "Visa, MasterCard, American Express, Discover",
                        "iban": "International Bank Account Numbers",
                        "routing_number": "US bank routing numbers",
                        "swift_code": "SWIFT/BIC codes"
                    },
                    "compliance": ["PCI-DSS", "GDPR"]
                },
                "medical": {
                    "description": "Healthcare data patterns (patient IDs, medical records)",
                    "patterns": {
                        "patient_id": "Patient identification numbers",
                        "medical_record": "Medical record numbers",
                        "npi": "National Provider Identifier",
                        "icd_code": "ICD diagnosis codes"
                    },
                    "compliance": ["HIPAA", "GDPR"]
                },
                "security": {
                    "description": "Security-related patterns (API keys, tokens)",
                    "patterns": {
                        "api_key": "Generic API keys",
                        "jwt_token": "JSON Web Tokens",
                        "oauth_token": "OAuth tokens",
                        "password_hash": "Password hashes"
                    },
                    "compliance": ["SOC2", "ISO27001"]
                },
                "cloud": {
                    "description": "Cloud provider patterns (AWS, Azure, GCP)",
                    "patterns": {
                        "aws_access_key": "AWS access keys",
                        "azure_key": "Azure storage keys",
                        "gcp_key": "GCP service account keys",
                        "docker_secret": "Docker secrets"
                    },
                    "compliance": ["SOC2", "ISO27001"]
                }
            }
        }
        """
    
    @server.resource("storm-logger://patterns/best-practices")
    def get_pattern_best_practices() -> str:
        """
        Get pattern management best practices.
        
        Returns:
            JSON string with best practices
        """
        return """
        {
            "pattern_best_practices": {
                "design_principles": {
                    "single_responsibility": "Each pattern matcher should handle one type of data",
                    "clear_naming": "Use descriptive names for patterns and matchers",
                    "priority_levels": "Use priority levels to handle conflicts",
                    "performance_aware": "Design patterns for high-volume processing"
                },
                "security_guidelines": {
                    "avoid_backtracking": "Prevent ReDoS attacks with careful regex design",
                    "validate_replacements": "Ensure replacement strings don't leak information",
                    "test_edge_cases": "Test patterns with malicious input",
                    "regular_updates": "Keep patterns updated with new threat vectors"
                },
                "maintenance_practices": {
                    "version_control": "Track pattern changes with version control",
                    "documentation": "Document each pattern's purpose and edge cases",
                    "testing": "Comprehensive test suites for all patterns",
                    "performance_monitoring": "Monitor pattern performance in production"
                },
                "storm_logger_integration": {
                    "business_metrics": "Track pattern performance as business metrics",
                    "compliance_reporting": "Generate compliance reports for pattern usage",
                    "enterprise_features": "Leverage Storm Logger's enterprise capabilities",
                    "sanitization_integration": "Integrate with Storm Logger's sanitization system"
                }
            }
        }
        """
    
    # Prompts
    @server.prompt
    def pattern_migration_strategy(
        current_patterns: str,
        target_system: str = "storm_logger",
        complexity_level: str = "medium"
    ) -> str:
        """
        Generate a comprehensive pattern migration strategy.
        
        Args:
            current_patterns: Description of current pattern system
            target_system: Target pattern system (storm_logger, custom)
            complexity_level: Complexity level (low, medium, high)
            
        Returns:
            Detailed migration strategy
        """
        return f"""
# Pattern Migration Strategy

## Current State Analysis
- **Current Patterns**: {current_patterns}
- **Target System**: {target_system}
- **Complexity Level**: {complexity_level}

## Migration Approach

### Phase 1: Assessment and Planning
1. **Inventory Current Patterns**
   - Document all existing regex patterns
   - Identify pattern conflicts and overlaps
   - Assess performance characteristics
   - Evaluate security implications

2. **Analyze Business Impact**
   - Identify critical patterns affecting revenue
   - Assess compliance requirements
   - Evaluate performance requirements
   - Document migration risks

### Phase 2: Pattern Modernization
1. **Escape Regex Hell**
   - Use `escape_regex_hell_convert_to_pattern` for complex patterns
   - Create clean PatternMatcher classes
   - Implement proper priority handling
   - Add comprehensive testing

2. **Leverage Pattern Libraries**
   - Use `no_more_regex_hell_pattern_library` for common patterns
   - Customize patterns for specific business needs
   - Implement security best practices
   - Add performance optimizations

### Phase 3: Implementation and Testing
1. **Gradual Migration**
   - Start with non-critical patterns
   - Implement parallel testing
   - Monitor performance metrics
   - Validate business outcomes

2. **Quality Assurance**
   - Use `debug_regex_hell_pattern_conflicts` for conflict resolution
   - Implement comprehensive test suites
   - Validate compliance requirements
   - Performance benchmarking

### Phase 4: Optimization and Monitoring
1. **Performance Tuning**
   - Use `optimize_pattern_performance` for high-volume scenarios
   - Monitor pattern execution metrics
   - Implement caching strategies
   - Regular performance reviews

2. **Security Validation**
   - Use `validate_pattern_security` for security assessment
   - Regular security audits
   - Compliance verification
   - Threat model updates

## Success Metrics
- **Performance**: 50% reduction in pattern execution time
- **Maintainability**: 80% reduction in pattern-related bugs
- **Security**: 100% compliance with security standards
- **Developer Experience**: 90% reduction in pattern debugging time

## Risk Mitigation
- Parallel testing during migration
- Comprehensive rollback procedures
- Performance monitoring and alerting
- Regular security assessments

This strategy ensures a smooth transition from regex hell to maintainable pattern management while supporting Storm Logger's enterprise goals.
"""
    
    @server.tool(tags={"health", "internal"})
    def health_check() -> Dict:
        """Health check for patterns server."""
        import time
        
        checks = {
            "server_operational": True,
            "tools_available": True,
            "pattern_management_module": False,
            "regex_analysis_module": False
        }
        
        # Test context logic modules with multiple import strategies
        # Try pattern_management module
        try:
            from ..context_logic import pattern_management
            checks["pattern_management_module"] = True
            checks["pattern_management_functions"] = len([attr for attr in dir(pattern_management) if not attr.startswith('_') and callable(getattr(pattern_management, attr))])
        except ImportError:
            try:
                from _mcp.context_logic import pattern_management
                checks["pattern_management_module"] = True
                checks["pattern_management_functions"] = len([attr for attr in dir(pattern_management) if not attr.startswith('_') and callable(getattr(pattern_management, attr))])
            except ImportError:
                try:
                    from context_logic import pattern_management
                    checks["pattern_management_module"] = True
                    checks["pattern_management_functions"] = len([attr for attr in dir(pattern_management) if not attr.startswith('_') and callable(getattr(pattern_management, attr))])
                except ImportError:
                    checks["pattern_management_module"] = False
        
        # Try regex_analysis module
        try:
            from ..context_logic import regex_analysis
            checks["regex_analysis_module"] = True
            checks["regex_analysis_functions"] = len([attr for attr in dir(regex_analysis) if not attr.startswith('_') and callable(getattr(regex_analysis, attr))])
        except ImportError:
            try:
                from _mcp.context_logic import regex_analysis
                checks["regex_analysis_module"] = True
                checks["regex_analysis_functions"] = len([attr for attr in dir(regex_analysis) if not attr.startswith('_') and callable(getattr(regex_analysis, attr))])
            except ImportError:
                try:
                    from context_logic import regex_analysis
                    checks["regex_analysis_module"] = True
                    checks["regex_analysis_functions"] = len([attr for attr in dir(regex_analysis) if not attr.startswith('_') and callable(getattr(regex_analysis, attr))])
                except ImportError:
                    checks["regex_analysis_module"] = False
        
        # Determine overall health status
        critical_checks = ["server_operational", "tools_available"]
        all_critical_pass = all(checks[check] for check in critical_checks)
        
        if all(checks.values()):
            status = "healthy"
        elif all_critical_pass:
            status = "warning"
        else:
            status = "error"
        
        return {
            "status": status,
            "checks": checks,
            "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "server": "patterns"
        }
    
    return server