import requests
from app.database.repository.communications_repository import (get_outgoing_whatsapp_communications_pending_messaging_with_contact_and_user_data
                                                                    , add_users_contacts_communications_replies)
import logging
import time

# Configure logging
logging.basicConfig(
    filename='log.txt',
    filemode='a',  # Append to the log file
    format='%(asctime)s - %(levelname)s - %(message)s',
    level=logging.INFO
)



def send_whatsapp_message(whatsapp_phone_no_id, recipient_phone_number, message_text, access_token):
    url = f"https://graph.facebook.com/v22.0/{whatsapp_phone_no_id}/messages"

    # Construct the payload as per WhatsApp API requirements
    post_fields = {
        'messaging_product': 'whatsapp',
        'to': recipient_phone_number,
        'type': 'text',
        'text': {
            'body': message_text
        }
    }

    # Set the headers, including the access token for authorization
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {access_token}'
    }

    try:
        # Make the POST request to send the message
        response = requests.post(url, json=post_fields, headers=headers)

        # Check for a successful response
        if response.status_code == 200:
            return response
        else:
            logging.error("Failed to send message to %s: %d - %s", recipient_phone_number, response.status_code,
                          response.text)
            return False  # Return False indicating failure
    except requests.exceptions.RequestException as e:
        logging.error("An error occurred while sending to %s: %s", recipient_phone_number, str(e))
        return False  # Return False indicating failure


def process_pending_unsent_communications():
    while True:
        communications_to_send = get_outgoing_whatsapp_communications_pending_messaging_with_contact_and_user_data()
        for communication in communications_to_send:
            whatsapp_phone_no_id = communication['user_whatsapp_phone_no_id']
            recipient_phone_number = communication['contact_whatsapp_number']
            message_text = communication['content']
            access_token = communication['user_whatsapp_bot_api_key']
            user_contact_communication_log_id = communication['user_contact_communication_log_id']

            # Send the WhatsApp message
            success = send_whatsapp_message(whatsapp_phone_no_id, recipient_phone_number, message_text, access_token)

            # If message sent successfully, log the entry in the database
            if success:
                try:
                    add_users_contacts_communications_replies(user_contact_communication_log_id, success, int(time.time()))
                except Exception as e:
                    logging.error("Failed to add database entry for %s: %s", recipient_phone_number, str(e))
            else:
                logging.warning("Failed to send message. No database entry created for %s", recipient_phone_number)
        time.sleep(5)



