from __future__ import annotations

from typing import Any, Dict
import re


_EXT_RX = re.compile(r"(?:ext\.?|extension|x|;ext=|#)\s*\d{1,6}\b|,\d{1,6}$", re.I)


def _strip_extension(num: str) -> str:
    if not num:
        return ""
    return _EXT_RX.sub("", num).strip()


def _e164_fallback(num: str, country: str) -> str:
    core = _strip_extension(num)
    digits = "".join(ch for ch in (core or "") if ch.isdigit())
    if not digits:
        return ""
    if len(digits) < 7 or len(digits) > 15:
        return ""
    country_upper = (country or "US").upper()
    if country_upper in {"US", "CA"}:
        if len(digits) == 11 and digits.startswith("1"):
            return f"+{digits}"
        if len(digits) == 10:
            return f"+1{digits}"
    return f"+{digits}"


def fix_phone_format(text: str, *, country: str = "US") -> Dict[str, Any]:
    try:
        import phonenumbers  # optional dep

        p = phonenumbers.parse(text or "", country or "US")
        if not phonenumbers.is_valid_number(p):
            return {"value": ""}
        return {
            "value": phonenumbers.format_number(
                p, phonenumbers.PhoneNumberFormat.E164
            )
        }
    except Exception:
        return {"value": _e164_fallback(text, country or "US")}
