import requests
from decimal import Decimal

from django.conf import settings
from userauth.models import MessageWhatsappTemplate
from django.template import Template, Context
import time
import logging
from userauth.models import MessageWhatsappTemplate
from django.http import JsonResponse
logger = logging.getLogger(__name__)
def send_whatsapp(phone,message):
    print(phone, message)
    if not phone or not message:
        return JsonResponse({"error": "phone و message الزامید"}, status=400)

    url = "https://wasenderapi.com/api/send-message"
    payload = {
        "to": phone,
        "text": message
    }
    headers = {
        "Authorization": f"Bearer {settings.WASENDER_API_KEY}",
        "Content-Type": "application/json"
    }
    print("start requests.post")
    print("***********************")
    print("***********************")

    try:
        resp = requests.post(url, json=payload, headers=headers, proxies={"http": None, "https": None})
        print("End requests.post")
        data = resp.json()
    except Exception as e:
        print("error=",e)
        return JsonResponse({"error": "خطا در پاسخ API", "text": resp.text}, status=resp.status_code)

    if resp.status_code != 200:
        return JsonResponse({"error": data.get("message", "خطا از سمت WasenderAPI"), "detail": data}, status=resp.status_code)

    return JsonResponse(data)

def send_wallet_notification(recipient_type, person, amount, wallet_after,phone):
    """Send WhatsApp notification for wallet changes"""
    try:
        if recipient_type == 'patient':
            name = person.get_full_name()
            template_type = 'patient_wallet'
        elif recipient_type == 'doctor':
            name = person.get_full_name()
            template_type = 'doctor_wallet'
        else:
            name = person.get_full_name()
            template_type = 'technician_wallet'

        message_template = MessageWhatsappTemplate.objects.get(message_type=template_type)
        template = Template(message_template.content)

        context_data = {
            f'{recipient_type}_name': name,
            'price': str(amount),
            f'{recipient_type}_wallet': str(wallet_after),
        }

        personalized_message = template.render(Context(context_data))
        send_whatsapp(settings.MANAGER_PHONE, personalized_message)
        # time.sleep(2)
        send_whatsapp(phone, personalized_message)
        # time.sleep(2)

    except Exception as e:
        logger.error(f"Failed to send WhatsApp notification: {str(e)}")

def send_wallet_cost_notification(recipient_type, person, amount, wallet_after,phone):
    """Send WhatsApp notification for wallet changes"""
    try:
        name = person.get_full_name()
        if recipient_type == 'patient':
            template_type = 'patient_add_wallet'
        elif recipient_type == 'doctor':
            template_type = 'doctor_add_wallet'
        else:
            template_type = 'technician_add_wallet'

        message_template = MessageWhatsappTemplate.objects.get(message_type=template_type)
        template = Template(message_template.content)

        context_data = {
            f'{recipient_type}_name': name,
            'price': str(amount),
            f'{recipient_type}_wallet': str(wallet_after),
        }

        personalized_message = template.render(Context(context_data))
        send_whatsapp(settings.MANAGER_PHONE, personalized_message)
        # time.sleep(2)
        send_whatsapp(phone, personalized_message)
        # time.sleep(2)

    except Exception as e:
        logger.error(f"Failed to send WhatsApp notification: {str(e)}")

def send_create_user_notification(recipient_type, person):
    """Send WhatsApp notification for wallet changes"""
    try:

        name = person.get_full_name()
        phone = person.country_code + person.phone_number
        if recipient_type == 'patient':
            template_type = 'patient_add_user'
        elif recipient_type == 'doctor':
            template_type = 'doctor_add_user'
        else:
            template_type = 'technician_add_user'

        message_template = MessageWhatsappTemplate.objects.get(message_type=template_type)
        template = Template(message_template.content)

        context_data = {
            f'{recipient_type}_name': name
        }

        personalized_message = template.render(Context(context_data))
        send_whatsapp(settings.MANAGER_PHONE, personalized_message)
        # time.sleep(2)
        send_whatsapp(phone, personalized_message)
        # time.sleep(2)

    except Exception as e:
        logger.error(f"Failed to send WhatsApp notification: {str(e)}")


def send_whatsapp_message(phone, message):
    """
    Wrapper around send_whatsapp with simplified return (True/False)
    """
    try:
        response = send_whatsapp(phone, message)
        time.sleep(2)
        return response.status_code == 200
    except Exception as e:
        logger.error(f"Error sending WhatsApp message: {e}")
        return False

def send_whatsapp2(phone,message):
    print("in send_whatsapp user=",phone,message)

    instance_id = settings.INSTANCE_ID

    if not phone or not message:
        return JsonResponse({"error": "phone و message  are required"}, status=400)

    url = f"https://waapi.app/api/v1/instances/{instance_id}/client/action/send-message"
    payload = {
        "chatId": f"{phone}@c.us",
        "message": message
    }
    headers = {
        "Authorization": f"Bearer {settings.WAAPI_API_KEY}",
        "Content-Type": "application/json"
    }
    print("payload=",payload)

    resp = requests.post(url, json=payload, headers=headers)
    print("resp=",resp)
    print("resp.status_code=",resp.status_code)
    try:
        try:
            data = resp.json()
            print(data)
        except ValueError:
            return JsonResponse({"error": "Error", "text": resp.text}, status=resp.status_code)

        if resp.status_code != 200:
            return JsonResponse({"error": data.get("message", "Error WaAPI"), "detail": data}, status=resp.status_code)

        return JsonResponse(data)
    except Exception as e:
        print("error=",e)

def send_whatsapp_message2(phone, message):
    print("in send_whatsapp_message=", phone, message)

    try:
        instance_id = settings.INSTANCE_ID
        api_key = settings.WAAPI_API_KEY

        url = f"https://waapi.app/api/v1/instances/{instance_id}/client/action/send-message"

        payload = {
            "chatId": f"{phone}@c.us",
            "message": message
        }

        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }

        response = requests.post(url, json=payload, headers=headers, timeout=30)
        print("response=",response)
        print("response.status_code =",response.status_code )
        if response.status_code == 200:
            logger.info(f"Message sent to {phone}")
            print(f"Message sent to {phone}")
            return True
        else:
            logger.error(f"Error sending message to {phone}: {response.text}")
            print(f"Error sending message to {phone}: {response.text}")
            return False

    except Exception as e:
        logger.error(f"Error in sending WhatsApp message: {str(e)}")
        print(f"Error in sending WhatsApp message: {str(e)}")
        return False