import re

from django.core.exceptions import ValidationError

DIGITS = str.maketrans('۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩', '01234567890123456789')


def normalize_phone(value):
    """Return Iranian mobile numbers in canonical E.164 form (+989xxxxxxxxx)."""
    phone = str(value or '').strip().translate(DIGITS)
    phone = re.sub(r'[\s\-()]', '', phone)
    if phone.startswith('0098'):
        phone = '+98' + phone[4:]
    elif phone.startswith('09'):
        phone = '+98' + phone[1:]
    elif re.fullmatch(r'9\d{9}', phone):
        phone = '+98' + phone
    elif phone.startswith('98'):
        phone = '+' + phone
    if not re.fullmatch(r'\+989\d{9}', phone):
        raise ValidationError('شماره موبایل معتبر وارد کنید؛ مانند 09123456789.')
    return phone
