 # Import the Twilio Client if using Twilio
import string
import random
# import boto3
# from botocore.exceptions import NoCredentialsError, ClientError
from django.conf import settings
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from asgiref.sync import sync_to_async
import asyncio
import logging

logger = logging.getLogger(__name__)
# AWS SES setup
# ses_client = boto3.client('ses', region_name=settings.AWS_S3_REGION_NAME,aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
#     aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)

# def send_email_to_client(data):
#     # Set default recipient if 'to_email' is not provided
#     # to_email = data.get('to_email', settings.DEFAULT_TO_EMAIL)
    
#     # Prepare the email components
#     try:
#         response = ses_client.send_email(
#             Source=settings.DEFAULT_FROM_EMAIL,
#             Destination={
#                 'ToAddresses': [data['to_email']],
#             },
#             Message={
#                 'Subject': {
#                     'Data': data['subject'],
#                 },
#                 'Body': {
#                     'Text': {
#                         'Data': data['body'],
#                     },
#                 },
#             }
#         )
#         return {
#             'status': 'success',
#             'status_code': response['ResponseMetadata']['HTTPStatusCode'],
#             'message_id': response['MessageId']
#         }
#     except (NoCredentialsError, ClientError) as e:
#         return {
#             'status': 'error',
#             'error': str(e)
#         }

# def send_email(data):
#     # Set default recipient if 'to_email' is not provided
#     # to_email = data.get('to_email', settings.DEFAULT_TO_EMAIL)
    
#     # Prepare the email with HTML content
#     try:
#         response = ses_client.send_email(
#             Source=settings.DEFAULT_FROM_EMAIL,
#             Destination={
#                 'ToAddresses': [data['to_email']],
#             },
#             Message={
#                 'Subject': {
#                     'Data': data['subject'],
#                 },
#                 'Body': {
#                     'Html': {
#                         'Data': data['body'],
#                     },
#                 },
#             }
#         )
#         return {
#             'status': 'success',
#             'status_code': response['ResponseMetadata']['HTTPStatusCode'],
#             'message_id': response['MessageId']
#         }
#     except (NoCredentialsError, ClientError) as e:
#         return {
#             'status': 'error',
#             'error': str(e)
#         }


# def 

# OTP verification which comes on mobile  number
def generate_otp(length=4):
    characters = string.digits
    otp = ''.join(random.choice(characters) for _ in range(length))
    return otp



import random
import string

def generate_strong_password():
    length = 12
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for i in range(length))
    return password


from .models import User

def generate_unique_referral_code(length=8):
    while True:
        code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
        if not User.objects.filter(referral_code=code).exists():
            return code


from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

# def send_email_to_client(data):
#     message = Mail(
#         from_email=settings.DEFAULT_FROM_EMAIL,
#         to_emails=data['to_email'],
#         subject=data['subject'],
#         plain_text_content=data['body']
#     )

#     try:
#         print("before")
#         sg = SendGridAPIClient('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')
#         print("beore neeche",message)
#         response = sg.send(message)
#         print(response,"hgfds")
#         return {
#             'status': 'success',
#             'status_code': response.status_code,
#             'body': response.body,
#             'headers': response.headers
#         }
#     except Exception as e:
#         return {
#             'status': 'error',
#             'error': str(e)
#         }
    
import requests
import json

def send_email_to_client(data):
    url = "https://api.sendgrid.com/v3/mail/send"
    headers = {
        "Authorization": f"Bearer {settings.SENDGRID_API_KEY}",
        "Content-Type": "application/json"
    }
    # print(settings.SENDGRID_API_KEY,"ghjkl")
    email_data = {
        "personalizations": [
            {
                "to": [
                    {
                        "email": data['to_email']
                    }
                ]
            }
        ],
        "from": {
            "email": settings.DEFAULT_FROM_EMAIL
        },
        "subject": data['subject'],
        "content": [
            {
                "type": "text/plain",
                "value": data['body']
            }
        ]
    }

    try:
        response = requests.post(url, headers=headers, data=json.dumps(email_data))
        if response.status_code == 202:
            return {
                'status': 'success',
                'status_code': response.status_code,
                'body': response.text,
                'headers': response.headers
            }
        else:
            return {
                'status': 'error',
                'status_code': response.status_code,
                'body': response.text
            }
    except Exception as e:
        return {
            'status': 'error',
            'error': str(e)
        }


def send_email(data):
    url = "https://api.sendgrid.com/v3/mail/send"
    headers = {
        "Authorization": f"Bearer {settings.SENDGRID_API_KEY}",
        "Content-Type": "application/json"
    }
    
    email_data = {
        "personalizations": [
            {
                "to": [
                    {
                        "email": data['to_email']
                    }
                ]
            }
        ],
        "from": {
            "email": settings.DEFAULT_FROM_EMAIL
        },
        "subject": data['subject'],
        "content": [
            {
                "type": "text/html",
                "value": data['body']
            }
        ]
    }

    try:
        response = requests.post(url, headers=headers, data=json.dumps(email_data))
        if response.status_code == 202:
            return {
                'status': 'success',
                'status_code': response.status_code,
                'body': response.text,
                'headers': response.headers
            }
        else:
            return {
                'status': 'error',
                'status_code': response.status_code,
                'body': response.text
            }
    except Exception as e:
        return {
            'status': 'error',
            'error': str(e)
        }

def send_email_otp(data):
    html_content =render_to_string('otp.html', {
        'otp': data['otp'],
    })
    url = "https://api.sendgrid.com/v3/mail/send"
    headers = {
        "Authorization": f"Bearer {settings.SENDGRID_API_KEY}",
        "Content-Type": "application/json"
    }
    
    email_data = {
        "personalizations": [
            {
                "to": [
                    {
                        "email": data['to_email']
                    }
                ]
            }
        ],
        "from": {
            "email": settings.DEFAULT_FROM_EMAIL
        },
        "subject": data['subject'],
        "content": [
            {
                "type": "text/html",
                "value": html_content
            }
        ]
    }

    try:
        response = requests.post(url, headers=headers, data=json.dumps(email_data))
        if response.status_code == 202:
            return {
                'status': 'success',
                'status_code': response.status_code,
                'body': response.text,
                'headers': response.headers
            }
        else:
            return {
                'status': 'error',
                'status_code': response.status_code,
                'body': response.text
            }
    except Exception as e:
        return {
            'status': 'error',
            'error': str(e)
        }

def send_approval_email(data):
    
    # Render the email template with context
    html_content = render_to_string('adminapprove.html', {
        'vendor_name': data['name'],
    })
    url = "https://api.sendgrid.com/v3/mail/send"
    headers = {
        "Authorization": f"Bearer {settings.SENDGRID_API_KEY}",
        "Content-Type": "application/json"
    }
    
    email_data = {
        "personalizations": [
            {
                "to": [
                    {
                        "email": data['to_email']
                    }
                ]
            }
        ],
        "from": {
            "email": settings.DEFAULT_FROM_EMAIL
        },
        "subject": data['subject'],
        "content": [
            {
                "type": "text/html",
                "value": html_content
            }
        ]
    }

    try:
        response = requests.post(url, headers=headers, data=json.dumps(email_data))
        if response.status_code == 202:
            return {
                'status': 'success',
                'status_code': response.status_code,
                'body': response.text,
                'headers': response.headers
            }
        else:
            return {
                'status': 'error',
                'status_code': response.status_code,
                'body': response.text
            }
    except Exception as e:
        return {
            'status': 'error',
            'error': str(e)
        }
def send_user_verify(data):
    
    # Render the email template with context
    html_content = render_to_string('accountverify.html', {
        'name': data['name'],
    })
    url = "https://api.sendgrid.com/v3/mail/send"
    headers = {
        "Authorization": "Bearer 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",
        "Content-Type": "application/json"
    }
    
    email_data = {
        "personalizations": [
            {
                "to": [
                    {
                        "email": data['to_email']
                    }
                ]
            }
        ],
        "from": {
            "email": settings.DEFAULT_FROM_EMAIL
        },
        "subject": data['subject'],
        "content": [
            {
                "type": "text/html",
                "value": html_content
            }
        ]
    }

    try:
        response = requests.post(url, headers=headers, data=json.dumps(email_data))
        if response.status_code == 202:
            return {
                'status': 'success',
                'status_code': response.status_code,
                'body': response.text,
                'headers': response.headers
            }
        else:
            return {
                'status': 'error',
                'status_code': response.status_code,
                'body': response.text
            }
    except Exception as e:
        return {
            'status': 'error',
            'error': str(e)
        }


def send_withdraw_otp_email(vendor_email, otp):
    try:
       
        logger.info(f"Preparing withdraw opt email for vendor: {vendor_email}")

        context = {
            "otp": otp
        }

        subject = f"Withdrawal OTP Verification"
        email_content = render_to_string("withdrawal_otp_email.html", context)

        message = Mail(
            from_email=settings.DEFAULT_FROM_EMAIL,
            to_emails=vendor_email,
            subject=subject,
            html_content=email_content,
        )

        sg = SendGridAPIClient(settings.SENDGRID_API_KEY)
        response = sg.send(message)

        logger.info(f"Otp sent to {vendor_email} for withdraw request")

    except Exception as e:
        logger.exception(f"Error sending otp for withdraw email to vendor {vendor_email}: {str(e)}")

# def send_vendor_order_email(order_item):
#     """
#     Sends an order notification email to the vendor with order details.
#     """
#     vendor = order_item.vendor
#     order = order_item.order_purchase
#     buyer = order.buyer
#     delivery_address = order.address

#     buyer_phone = buyer.phone if buyer.phone else None

#     if vendor.email:
#         subject = f"New Order Received - {order_item.product.title}"

#         # Render email template
#         email_content = render_to_string("vendor_order_email.html", {
#             "vendor": vendor,
#             "order_item": order_item,
#             "buyer": buyer,
#             "delivery_address": delivery_address,
#             "buyer_phone": buyer_phone
#         })

#         # Send email
#         email = EmailMessage(
#             subject=subject,
#             body=email_content,
#             from_email=settings.DEFAULT_FROM_EMAIL,
#             to=[vendor.email],
#         )
#         email.content_subtype = "html"
#         email.send(fail_silently=False)

# async def send_vendor_order_email_async(order_item):
#     """Wraps the synchronous email sending function inside an async-safe wrapper."""
#     await sync_to_async(send_vendor_order_email, thread_sensitive=True)(order_item)


# def send_vendor_order_email(order_item):
   
#     vendor = order_item.vendor
#     order = order_item.order_purchase
#     buyer = order.buyer
#     delivery_address = order.address
#     buyer_phone = buyer.phone if buyer.phone else None

#     if vendor.email:
#         subject = f"New Order Received - {order_item.product.title}"
        
#         # Render email template without "templates/" prefix
#         email_content = render_to_string("vendor_order_email.html", {
#             "vendor": vendor,
#             "order_item": order_item,
#             "buyer": buyer,
#             "delivery_address": delivery_address,
#              "buyer_phone": buyer_phone 
#         })

#         # Send email
#         email = EmailMessage(
#             subject=subject,
#             body=email_content,
#             from_email=settings.DEFAULT_FROM_EMAIL,
#             to=[vendor.email],
#         )
#         email.content_subtype = "html"  # Ensure the email is sent as HTML
#         email.send(fail_silently=False)
        # await sync_to_async(email.send)(fail_silently=False)
        # await sync_to_async(email.send, thread_sensitive=True)(fail_silently=False)



