"""Phone number normalization for login-by-phone — Tanzanian numbers get
written as 07XXXXXXXX, 2557XXXXXXXX, or +2557XXXXXXXX depending on the
person, so login needs to try the plausible equivalents of whatever was typed."""

import re


def normalize_phone_variants(raw):
    """Returns the set of plausible stored forms for a typed phone number,
    so login matches regardless of which format the account was saved with."""
    digits = re.sub(r'\D', '', raw or '')
    if not digits:
        return []

    variants = {digits}
    if digits.startswith('0') and len(digits) == 10:
        variants.add('255' + digits[1:])
        variants.add('+255' + digits[1:])
    elif digits.startswith('255') and len(digits) == 12:
        variants.add('0' + digits[3:])
        variants.add('+' + digits)
    return list(variants)


def canonical_phone(raw):
    """Normalizes a phone number to a single consistent stored form (local
    0XXXXXXXXX where recognizable) so it doesn't matter how the person typed
    it at signup — login-time matching then just has to produce the same
    canonical form to compare against."""
    digits = re.sub(r'\D', '', raw or '')
    if not digits:
        return ''
    if digits.startswith('255') and len(digits) == 12:
        return '0' + digits[3:]
    return digits


def to_international(raw):
    """Converts a stored phone number (usually local 0XXXXXXXXX) to the
    255XXXXXXXXX form SMS providers expect. Returns '' if it doesn't look
    like a plausible Tanzanian number, so callers can skip sending rather
    than fire an SMS at a malformed number."""
    digits = re.sub(r'\D', '', raw or '')
    if not digits:
        return ''
    if digits.startswith('0') and len(digits) == 10:
        return '255' + digits[1:]
    if digits.startswith('255') and len(digits) == 12:
        return digits
    return ''
