from django.core.exceptions import ImproperlyConfigured
from rest_framework.status import HTTP_200_OK, HTTP_500_INTERNAL_SERVER_ERROR, HTTP_502_BAD_GATEWAY, HTTP_401_UNAUTHORIZED
from ...services.sms_services.sms_kavenegar import KavenegarCom
from ...services.sms_services.sms_melipayamak import MeliPayamakCom
from ...services.sms_services.sms_parsianweb import ParsianWebcoIr
from ...settings import sms_init_check


def send_message(mobile_number, message_text, data=None, template_id=None):
    try:
        icheck = sms_init_check()
        if not (icheck and isinstance(icheck, dict) and 'SMS_SERVICE' in icheck and 'SETTINGS' in icheck):
            raise 'SMS service settings are not configured correctly.'

    except ImproperlyConfigured as e:
            print(f"Configuration Error: {e}")
            raise
    
    sms_service = icheck['SMS_SERVICE']
    options = icheck['SETTINGS']

    if sms_service == 'PARSIAN_WEBCO_IR':
        try:
            if not template_id:
                template_id = data.get('template_id')
                if not template_id:
                    raise ImproperlyConfigured('template_id is required for the PARSIAN_WEBCO_IR service.')
            service = ParsianWebcoIr(mobile=mobile_number, options=options)
            response = service.send_message(message=message_text, template_id=template_id)
            response = service.generate_response(response, mobile_number, message_text)

        except ImproperlyConfigured as e:
            print(f"Configuration Error: {e}")
            raise

    elif sms_service == 'MELI_PAYAMAK_COM':
        service = MeliPayamakCom(mobile=mobile_number, options=options)
        response = service.send_message(message=message_text)
        response = service.generate_response(response, mobile_number, message_text)

    elif sms_service == 'KAVENEGAR_COM':
        service = KavenegarCom(mobile=mobile_number, options=options)
        try:
            if template_id or data.get('template_id'):
                if not template_id:
                    template_id = data.get('template_id')
                _data = service.detect_tokens_from_data(data)
                response = service.send_message_lookup(message=message_text, template_id=template_id, **_data)
            else:
                response = service.send_message(message=message_text)
            response = service.generate_response(response)
            
        except (ValueError, KeyError, IndexError) as e:
            # obj_status = 502
            return False, {'details': 'Invalid response structure.', 'error': str(e)}

    return response