from twilio.rest import Client
from django.conf import settings
import logging
from typing import Optional

logger = logging.getLogger(__name__)
_twilio_api_client = None
_twilio_client = None
_twilio_sms_client = None

TWILIO_FROM_NUMBER= settings.TWILIO_FROM_NUMBER

def get_twilio_credentials():
    return settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN

def get_twilio_api_client() -> Client:
    """Return a singleton Twilio API client using Django settings."""
    global _twilio_api_client
    if _twilio_api_client is None:
        _twilio_api_client = Client(
            settings.TWILIO_API_KEY_SID,
            settings.TWILIO_API_KEY_SECRET,
            settings.TWILIO_ACCOUNT_SID,
        )
    return _twilio_api_client


def get_twilio_client() -> Client:
    """Return a singleton Twilio client using Django settings."""
    global _twilio_client
    if _twilio_client is None:
        _twilio_client = Client(
            settings.TWILIO_ACCOUNT_SID,
            settings.TWILIO_AUTH_TOKEN,
        )
    return _twilio_client


def get_caller_name_by_phone_number(phone_number: str) -> Optional[str]:
    """
    Retrieve phone number owner name from Twilio

    Args:
        phone_number: The phone number in E.164 format

    Returns:
        A string containing name
    """
    if not phone_number or not phone_number.strip():
            return None

    try:
        lookup_result = (
            get_twilio_api_client()
            .lookups.v2.phone_numbers(phone_number)
            .fetch(fields=["caller_name"])
        )

        caller_name = (
            lookup_result.caller_name.get("caller_name")
            if getattr(lookup_result, "caller_name", None)
            else None
        )

        if caller_name and caller_name.strip() and "unknown" not in caller_name.lower():
            return caller_name.strip()

    except Exception:
        logger.exception("Twilio lookup failed")

    return None
