\
import re
from typing import Optional


def normalizar_telefono(
    raw: object,
    country_code: str = "51",
) -> Optional[str]:
    """
    Normalización inicial para celulares peruanos.

    Acepta, por ejemplo:
      910005139
      +51 910 005 139
      51910005139
      0051 910005139

    Devuelve:
      +51910005139

    Si el número no parece un celular peruano válido de 9 dígitos
    comenzando en 9, devuelve None.
    """
    if raw is None:
        return None

    text = str(raw).strip()
    if not text:
        return None

    digits = re.sub(r"\D", "", text)

    if digits.startswith("00"):
        digits = digits[2:]

    # Número nacional peruano: 9 dígitos y empieza en 9.
    if len(digits) == 9 and digits.startswith("9"):
        return f"+{country_code}{digits}"

    # Número ya incluye código de país 51.
    if (
        digits.startswith(country_code)
        and len(digits) == len(country_code) + 9
        and digits[len(country_code)] == "9"
    ):
        return f"+{digits}"

    return None
