import re

# Ethiopian mobile numbers: 9 digits starting with 7 or 9, optionally
# prefixed with a leading 0 (local dialing) or the +251/251 country code.
_ET_MOBILE = re.compile(r"^(?:\+251|251|0)?([79]\d{8})$")


class InvalidPhoneNumber(ValueError):
    """Raised when a phone number isn't a valid Ethiopian mobile number."""


def normalize_ethiopian_phone(raw: str) -> str:
    """Normalize an Ethiopian mobile number to E.164 (+2519XXXXXXXX).

    Accepts local (09XXXXXXXX), national (9XXXXXXXX), and international
    (+2519XXXXXXXX / 2519XXXXXXXX) forms.
    """
    if not raw or not raw.strip():
        raise InvalidPhoneNumber("Phone number is required.")

    cleaned = re.sub(r"[\s\-]", "", raw.strip())
    match = _ET_MOBILE.match(cleaned)
    if not match:
        raise InvalidPhoneNumber(
            "Enter a valid Ethiopian phone number, e.g. 09XXXXXXXX."
        )
    return f"+251{match.group(1)}"
