from celery import shared_task
import logging
from apps.calls.services import get_twilio_client
from django.conf import settings

logger = logging.getLogger(__name__)


@shared_task(
    bind=True,
    max_retries=3,
    default_retry_delay=10  # 10 seconds retry delay
)
def send_sms_task(self, to_number: str, message: str):
    """
    Celery task to send SMS asynchronously using Twilio.
    Retries automatically on failure.
    """
    try:
        if not to_number:
            logger.error("Celery SMS task failed: no destination number provided.")
            return False

        twilio_client = get_twilio_client()

        sms = twilio_client.messages.create(
            body=message,
            from_=settings.TWILIO_FROM_NUMBER,
            to=to_number
        )

        logger.info(f"[CELERY] SMS sent to {to_number}, SID={sms.sid}")
        return True

    except Exception as exc:
        logger.exception(f"[CELERY] Twilio SMS send failed, will retry. Error: {exc}")
        raise self.retry(exc=exc)
