"""
Validation utilities for appointment scheduling and other user inputs
"""

import re
import logging

# Set up logger
logger = logging.getLogger("mango_ai_agent")

def validate_email(email: str) -> bool:
    """
    Validate an email address
    
    Args:
        email: The email address to validate
        
    Returns:
        bool: True if valid, False otherwise
    """
    if not email:
        return False
        
    # Basic pattern for email validation
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    
    # Check if the email matches the pattern
    if not re.match(pattern, email):
        logger.info(f"Email validation failed for: {email}")
        return False
    
    # Additional checks
    # Check for common domains to avoid typos
    common_domains = [
        "gmail.com", "yahoo.com", "hotmail.com", "outlook.com", 
        "aol.com", "icloud.com", "protonmail.com", "mail.com"
    ]
    
    domain = email.split('@')[-1].lower()
    
    # Check for common typos in domains
    typo_domains = {
        "gmail.co": "gmail.com",
        "gmail.cm": "gmail.com",
        "gamil.com": "gmail.com",
        "gmal.com": "gmail.com",
        "yahoo.co": "yahoo.com",
        "yaho.com": "yahoo.com",
        "hotmail.co": "hotmail.com",
        "hotmial.com": "hotmail.com",
        "outlook.co": "outlook.com"
    }
    
    if domain in typo_domains:
        logger.warning(f"Possible typo in email domain: {domain}, did you mean {typo_domains[domain]}?")
        # We still return True but log the warning
    
    logger.info(f"Email validation passed for: {email}")
    return True

def validate_phone(phone: str) -> bool:
    """
    Validate a phone number
    
    Args:
        phone: The phone number to validate
        
    Returns:
        bool: True if valid, False otherwise
    """
    if not phone:
        return False
    
    # Remove all non-digit characters for normalization
    digits_only = re.sub(r'\D', '', phone)
    
    # Check if we have a reasonable number of digits
    # Most countries have between 7 and 15 digits including country code
    if len(digits_only) < 7 or len(digits_only) > 15:
        logger.info(f"Phone validation failed for: {phone} - invalid length")
        return False
    
    # For international numbers, should start with a country code
    # For simplicity, we'll just check that it's a reasonable format
    # In a production system, you might want to use a library like phonenumbers
    
    # Basic pattern check - this is a simplified version
    pattern = r'^(?:\+?[0-9]{1,3}[-.\s]?)?(?:\(?[0-9]{3}\)?[-.\s]?)?[0-9]{3}[-.\s]?[0-9]{4}$'
    if not re.match(pattern, phone):
        logger.info(f"Phone validation failed for: {phone} - invalid format")
        return False
    
    logger.info(f"Phone validation passed for: {phone}")
    return True

def get_validation_feedback(field: str, value: str) -> str:
    """
    Get feedback for validation failures
    
    Args:
        field: The field that failed validation
        value: The value that failed validation
        
    Returns:
        str: Feedback message
    """
    if field == "email":
        return (
            f"The email address '{value}' doesn't appear to be valid. "
            "Please provide a valid email address in the format 'user@example.com'."
        )
    elif field == "phone":
        return (
            f"The phone number '{value}' doesn't appear to be valid. "
            "Please provide a valid phone number with area code, e.g., '123-456-7890'."
        )
    else:
        return f"The {field} '{value}' doesn't appear to be valid. Please try again."
