from groq import Groq
import gradio as gr
import os
import json
import random
from getvalues import getValues
from datetime import datetime, timedelta
import uuid
import re

api1 = os.getenv("Groq_key")
api2 = os.getenv("GRoq_key")

apis = [
    api1,
    api2,
]

def responsenew(data):
    idval = random.randint(1, 1000000000)
    print(f"\n\n{data}")
    newdata = data.replace("'", '"')
    items = json.loads(newdata)
    query = items['text']
    query = query.lower()
    
    
    while True:
        for api in apis:
            client = Groq(
                    api_key=api,
                )  # Configure the model with the API key
           
            try:
                response = client.chat.completions.create(
                messages=[
                    {
                        "role": "user",
                        "content": query,
                    }
                ],
                model="mixtral-8x7b-32768",
                )
                answer = response.choices[0].message.content
            except Exception as e:
                print(f"API call failed for: {e}")
            if answer:
                break
        if answer:
                break
    print(f"\n{answer}")
    if query is not None:
        if "remind me" in query:
            values = getValues(query)
            if values[0] is not None:
                msg = values[0]
            else:
                msg = "Reminder Alert"
            if values[1] is not None:
                time = values[1]
            else:
                time = "5:00 PM"
                # time = time1 + timedelta(hours=1)
                # time = time2.strftime("%d-%m-%Y %H:%M:%S.%f")
            if values[2] is not None:
                day = values[2]
            else:
                day = "today"
            if values[3] is not None:
                date = values[3]
            else:
                date = datetime.today()
            if values[4] is not None:
                reps = values[4]
            else:
                reps = "Once"
            respo = {
                'message': f"Message: {msg} \nTime: {time} \nDay: {day} \nCreated Successfully.",
                'action': "create_reminder",
                'function': {
                        'id': idval,
                        'sound': 'General',
                        'subTitle': 'Task',
                        'type': 'Note',
                        'title': msg,
                        'description': '',
                        'time': time.upper(),
                        'timestamp' : datetime.now().strftime("%d-%m-%Y %H:%M:%S.%f"),
                        'enable': False,
                        'report': [],
                        'icon': 'https://firebasestorage.googleapis.com/v0/b/cosmo-f5007.appspot.com/o/categories%2FIcons%2Ftaskicon.svg?alt=media&token=56f3fc55-8eda-4463-bceb-7bf3198dff3c',
                        'color': 'FFD700',
                        'sharedToMe': [],
                        'sharedByMe': [],
                        'repeat': reps,
                        'reminders': [{
                            'time': time.upper(),
                            'enable': False,
                            'repeat': reps,
                            'title': msg,
                            'id': idval,
                            'note': '',
                            'dates': [],
                            }],
                    }
            }

        elif "add to do" in query:
            replaced_string = text.replace("add todo", "").replace("add to do","")
            # 1. Replace "note down" with an empty string:
            replaced_string = text.replace("note down", "")
            
            # 2. Split the string into words:
            words = replaced_string.split()
            
            # 3. Extract the first two words:
            first_two_words = words[:2]  # Get the first two elements of the list
            
            # 4. Join the words back into a string (if needed):
            result_string = " ".join(first_two_words)
            respo = {
            'message': "Todo added!",
            'action': "create_todo",
            'function': {
                'name': result_string,
                'id': idval,
                'subTasks': [{
                    'task':replaced_string,
                    'done': False
                }],
                'shared': [],
                'sharedByMe': [],
                    },
            }
        elif "note down" in query:
            # 1. Replace "note down" with an empty string:
            replaced_string = text.replace("note down", "")
            
            # 2. Split the string into words:
            words = replaced_string.split()
            
            # 3. Extract the first two words:
            first_two_words = words[:2]  # Get the first two elements of the list
            
            # 4. Join the words back into a string (if needed):
            result_string = " ".join(first_two_words)
            respo = {
            'message': "Got it! Saved to your notes.",
            'action': "create_note",
            'function': {
                'title': result_string,
                'id': idval,
                'type': 'Note',
                'description': replaced_string,
                'time': datetime.now().strftime("%d/%m/%Y"),
                'mainTime': datetime.now().strftime("%I:%M %p"),
                'complete': False,
                'shared': [],
                'sharedByMe': [],
                }
            }
        elif "add coins" in query:
            respo = {
                "message": "Click the button below to view Premium Services and Coin Recharge options: ",
                "action": "payment",
                "function": "nothing",
            }
        elif "show my friends" in query:
            respo = {
                "message": "Here's the list of your friends: ",
                "action": "show_friends",
                "function": "nothing",
            }
        elif "show my groups" in query:
            respo = {
                "message": "You are member of following groups: ",
                "action": "show_mygroups",
                "function": "nothing",
            }
        elif "show my communities" in query:
            respo = {
                "message": "You are part of following communities🫶: ",
                "action": "show_mycommunities",
                "function": "nothing",
            }
        elif "show shared reminders" in query:
            respo = {
                "message": "Here's the list of your shared reminders: ",
                "action": "shared_reminders",
                "function": "nothing",
            }
        elif "create a post" in query:
            respo = {
                "message": "Sure!",
                "action": "create_post",
                "function": "nothing",
            }
        elif "show my routines" in query:
            respo = {
                "message": "Here's the list of your routines: ",
                "action": "myroutines",
                "function": "nothing",
            }
        # elif "what is your name" or "what's your name" or "who are you" in data:
        #     respo = {
        #         "message": "My name is Cosmo. I am your friendly personal assistant.",
        #         "action": "nothing",
        #         "function": "nothing",
        #     }
        elif "notify" in query:
            respo = {
                "message": "Select your friends to notify",
                "action": "send_notify",
                "function": "nothing",
            }
        elif "show actions" in query:
            respo = {
                "message": "Here is list of actions you can use:",
                "action": "show_actions",
                "function": "nothing",
            }
        else:
            respo = {
                "message": answer,
                "action": "nothing",
                "function": "nothing",
            }
    else:
        respo = {
            "message": "Whoops, seems like we're a bit overloaded! Don't worry, your request is in the queue and we'll get back to you as soon as possible.",
            "action": "nothing",
            "function": "nothing",
        }
    return json.dumps(respo)
    
    

gradio_interface = gr.Interface(fn=responsenew, inputs="text", outputs="text")
gradio_interface.launch()