"""Security utilities"""
import hashlib
import hmac
from typing import Optional
from app.core.logging import get_logger

logger = get_logger(__name__)


class WebhookValidator:
    """Validate Facebook webhook signatures"""
    
    @staticmethod
    def validate_signature(
        payload: bytes,
        signature: Optional[str],
        app_secret: str
    ) -> bool:
        """
        Validate Facebook webhook signature using HMAC-SHA256
        
        Args:
            payload: Raw request body
            signature: X-Hub-Signature-256 header value
            app_secret: Facebook app secret
            
        Returns:
            True if signature is valid, False otherwise
        """
        if not signature:
            logger.warning("Missing signature header")
            return False
        
        try:
            # Remove 'sha256=' prefix
            if signature.startswith('sha256='):
                signature = signature[7:]
            
            # Calculate expected signature
            expected_signature = hmac.new(
                app_secret.encode(),
                payload,
                hashlib.sha256
            ).hexdigest()
            
            # Constant-time comparison
            return hmac.compare_digest(signature, expected_signature)
            
        except Exception as e:
            logger.error(f"Signature validation error: {e}")
            return False


def sanitize_input(text: str, max_length: int = 5000) -> str:
    """Sanitize user input"""
    if not text:
        return ""
    
    # Truncate to max length
    text = text[:max_length]
    
    # Remove null bytes
    text = text.replace('\x00', '')
    
    return text.strip()
