import os
import logging

logger = logging.getLogger(__name__)

# Account deletion threshold in hours
# Default: 720 hours (30 days)
# Minimum: 24 hours (1 day)
# Maximum: 720 hours (30 days)

try:
    ACCOUNT_DELETION_THRESHOLD_HOURS = int(os.getenv('ACCOUNT_DELETION_THRESHOLD_HOURS', '720'))
except ValueError as e:
    raise ValueError(
        f"ACCOUNT_DELETION_THRESHOLD_HOURS must be a valid integer. "
        f"Invalid value: {os.getenv('ACCOUNT_DELETION_THRESHOLD_HOURS')}"
    ) from e

# Validation
MIN_THRESHOLD_HOURS = 24
MAX_THRESHOLD_HOURS = 720

def validate_threshold(threshold_hours=None):
    """
    Validate the account deletion threshold.
    
    Args:
        threshold_hours: Optional threshold value to validate. If None, validates the module's global value.
        
    Returns True if valid, raises ValueError if invalid.
    """
    value = threshold_hours if threshold_hours is not None else ACCOUNT_DELETION_THRESHOLD_HOURS
    
    if value < MIN_THRESHOLD_HOURS:
        raise ValueError(
            f"ACCOUNT_DELETION_THRESHOLD_HOURS must be at least {MIN_THRESHOLD_HOURS} hours. "
            f"Current value: {value}"
        )
    
    if value > MAX_THRESHOLD_HOURS:
        raise ValueError(
            f"ACCOUNT_DELETION_THRESHOLD_HOURS must be at most {MAX_THRESHOLD_HOURS} hours. "
            f"Current value: {value}"
        )
    
    # Warn if threshold is less than 7 days (168 hours)
    if value < 168:
        logger.warning(
            f"Account deletion threshold is set to {value} hours, "
            "which is below the recommended minimum of 7 days (168 hours). "
            "Users will have limited time to recover their accounts."
        )
    
    if threshold_hours is None:
        # Only log this when validating the module's global value
        logger.info(f"Account deletion threshold: {ACCOUNT_DELETION_THRESHOLD_HOURS} hours")
    
    return True

# Validate on module import
validate_threshold()