import requests
from settings.models import WhatsappInstance
import re


def replace_keys_with_values(text, key_value_map):
    try:
        def replacer(match):
            key = match.group(1)
            return key_value_map.get(key, "NA")

        # Regular expression to find placeholders like {{some_key}}
        return re.sub(r"{{(.*?)}}", replacer, text)

    except Exception as e:
        # Log the error message and return the original text
        print(f"Error occurred: {e}")
        return text


instanceID = "6676C7971633A"
accessToken = "6676c6d0af68c"


def send_message(number, message):
    try:
        instence = WhatsappInstance.objects.last()
        if instence:
            instanceID = instence.instance_id
            accessToken = instence.access_token
            api_domain = instence.api_domain

            url = f"https://{api_domain}/api/send?number=91{number}&type=text&message={message}&instance_id={instanceID}&access_token={accessToken}"

            payload = {}
            headers = {"Cookie": "stackpost_session=b4t1tuvbbr35hpkhi05h0vgamd9ki9og"}

            response = requests.request("GET", url, headers=headers, data=payload)

            print("------------", response.json())
    except Exception as ex:
        print(ex)


# # Example usage
# number = "919837994101"
# message = "Hi Neeraj"

# response = send_message(number, message)
# print(response)
