
def validate_abn(abn):
    """ABN validation with format cleaning and checksum validation"""
    if not abn:
        return False
    
    # Clean the ABN - remove spaces and common formatting
    clean_abn = abn.replace(' ', '').replace('-', '')
    
    # Check if it's 11 digits
    if len(clean_abn) != 11 or not clean_abn.isdigit():
        return False
    
    # Use the proper Australian checksum validation
    return validate_australian_business_number(clean_abn)


def validate_australian_business_number(abn):
    """
    Validate ABN using the official 88/99 weighting method
    As per Australian Taxation Office specifications
    """
    if not abn or len(abn) != 11 or not abn.isdigit():
        return False

    # ATO weighting factors
    weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
    total = 0
    
    for i, digit in enumerate(abn):
        digit = int(digit)
        if i == 0:
            digit -= 1  # Subtract 1 from first digit
        total += digit * weights[i]

    return total % 89 == 0


def validate_email(email):
    """Basic email validation"""
    if not email or '@' not in email:
        return False
    
    parts = email.split('@')
    if len(parts) != 2:
        return False
    
    local, domain = parts
    if not local or not domain or '.' not in domain:
        return False
    
    return True


def validate_phone_number(phone):
    """Validate Australian phone number format"""
    if not phone:
        return False
    
    # Remove spaces and common formatting
    clean_phone = phone.replace(' ', '').replace('-', '').replace('(', '').replace(')', '')
    
    # Australian mobile: 04xx xxx xxx or landline: 0x xxxx xxxx
    if clean_phone.startswith('04') and len(clean_phone) == 10:
        return True
    if clean_phone.startswith('0') and len(clean_phone) == 10:
        return True
    
    return False


def validate_rating_data(data):
    """Validate rating data for contract reviews"""
    if not data:
        return False, "No data provided"
    
    # Check required fields
    required_fields = ['overall_rating', 'quality_rating', 'communication_rating', 'safety_rating']
    for field in required_fields:
        if field not in data:
            return False, f"Missing required field: {field}"
        
        # Check rating is between 1-5
        try:
            rating = int(data[field])
            if not (1 <= rating <= 5):
                return False, f"{field} must be between 1 and 5"
        except (ValueError, TypeError):
            return False, f"Invalid {field} value"
    
    return True, "Valid rating data"
