########################################################################################################################
# IMPORTS

import re
from typing import Literal

import phonenumbers

########################################################################################################################
# FUNCTIONS


def parse_phone_number(
    number: str, country_code: str, output_format: Literal["national", "e164"] = "e164"
) -> str | None:
    """
    Clean and standardize phone number using the 'phonenumbers' library.

    Args:
        number (str): phone number
        country_code (str): ISO 3166-1 alpha-2 country code. It is case-insensitive
                            (e.g., 'es', 'ES', 'pt', 'US').
        output_format (Literal["national", "e164"]): Format to return. Defaults to "national"
                                                     to maintain backward compatibility.

    Returns:
        str | None: standardized phone number in the requested format without spaces,
                    or None if invalid.
    """
    if not number:
        return None

    try:
        parsed_number = phonenumbers.parse(str(number), country_code.upper())

        if phonenumbers.is_valid_number(parsed_number):
            if output_format == "e164":
                return phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumberFormat.E164)
            else:
                national_fmt = phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumberFormat.NATIONAL)
                return re.sub(r"\D", "", national_fmt)

        return None

    except phonenumbers.NumberParseException:
        return None
