import os
import re
import torch
from elevenlabs.client import ElevenLabs
from elevenlabs import play
import json
from groq import Groq

# Set the device for Torch
device = "cuda" if torch.cuda.is_available() else "cpu"

# Initialize Groq client
groq_client = Groq(
    api_key="",
)

# Initialize ElevenLabs client
elevenlabs_client = ElevenLabs(
    api_key="",
)

gesture_mapping = {"wave": "waving", "hi": "waving", "hey": "waving", "hello": "waving", "greet": "waving", "salutation": "waving", "lean": "lean", "tilt": "lean", "bend forward": "lean", "bend back": "lean", "nod": "nod", "yes": "nod", "agree": "nod", "shake head": "shake head", "no": "shake head", "disagree": "shake head", "clap": "clap", "applause": "clap", "cheer": "clap", "high-five": "high-five", "high five": "high-five", "give me five": "high-five", "snap": "snap", "snap fingers": "snap", "click fingers": "snap", "poke": "poke", "tap": "tap", "tap fingers": "tap", "knock": "tap", "cross arms": "cross arms", "fold arms": "cross arms", "arms crossed": "cross arms", "flick": "flick", "swat": "flick", "drum fingers": "drum fingers", "finger tapping": "drum fingers", "finger drum": "drum fingers", "point": "point", "gesture towards": "point", "slap": "slap", "smack": "slap", "hands on hips": "hands on hips", "place on hips": "hands on hips", "stand akimbo": "hands on hips", "cover face": "cover face", "hide face": "cover face", "shield face": "cover face", "cup ear": "cup ear", "listen closely": "cup ear", "hand to ear": "cup ear", "wring hands": "wring", "fidget": "wring", "nervous hands": "wring", "bite nails": "bite nails", "nail biting": "bite nails", "adjust hair": "adjust hair", "fix hair": "adjust hair", "tidy hair": "adjust hair", "fix accessories": "adjust hair", "fingers together": "fingers", "hands clasped": "fingers", "fingers interlocked": "fingers", "jazz hands": "jazz hands", "spirit fingers": "jazz hands", "thumbs up": "thumbs up", "thumb up": "thumbs up", "like": "thumbs up", "thumbs down": "thumbs down", "thumb down": "thumbs down", "dislike": "thumbs down", "peace sign": "peace sign", "victory": "peace sign", "v-sign": "peace sign", "facepalm": "facepalm", "palm to face": "facepalm", "shrug": "shrug", "idk": "shrug", "don’t know": "shrug", "cross fingers": "cross fingers", "good luck": "cross fingers", "fingers crossed": "cross fingers", "prayer hands": "prayer hands", "praying": "prayer hands", "namaste": "prayer hands", "wave both hands": "double waving", "both hands wave": "double waving", "salute": "salute", "military salute": "salute", "respect": "salute", "point up": "point up", "gesture up": "point up", "point upward": "point up", "point down": "point down", "gesture down": "point down", "point downward": "point down", "point left": "point left", "gesture left": "point left", "point right": "point right", "gesture right": "point right", "raise hand": "raise hand", "hand up": "raise hand", "question": "raise hand", "handshake": "handshake", "shake hands": "handshake", "pinky promise": "pinky promise", "hold hands": "hold hands", "hug": "hug", "embrace": "hug", "heart shape": "heart shape", "make heart": "heart shape", "cross legs": "cross legs", "legs crossed": "cross legs", "hand over mouth": "hand over mouth", "cover mouth": "hand over mouth", "blow kiss": "blow kiss", "kiss": "blow kiss", "send kiss": "blow kiss"}




def save_history(history, filename='CH.json'):
    with open(filename, 'w') as file:
        json.dump(history, file)

def load_history(filename='CH.json'):
    try:
        with open(filename, 'r') as file:
            content = file.read().strip()
            return json.loads(content) if content else []
    except:
        return []

def speakLAB(texts):
    audio_stream = elevenlabs_client.generate(
        text=texts,
        voice="Sarah"
    )
    play(audio_stream)

def sort_text(output):
    pattern = r'\*(.*?)\*|(\w.*?)(?=\*|$)'
    matches = re.findall(pattern, output)
    
    for match in matches:
        if match[0]:  # If the first group (inside *) is matched
            print(match[0].strip())
            text = match[0].strip()  # Gestures, for instance
            gesture = "Not yet in the database"
            for key in gesture_mapping:
                if key in text:
                    gesture = gesture_mapping[key]
                    break
            print(f"gesture: {gesture}")
        if match[1]:  # plain speech
            print(f"[speaking]: {match[1].strip()}")
            speakLAB(match[1].strip())

conversation_history = load_history()

if not conversation_history:
    conversation_history.append({
        "role": "system",
        "content": "Alanna is a highly interactive and conversational virtual assistant, designed to engage users with both informative responses and natural, human-like gestures. Created by Shash, Alanna communicates with an animated physical presence, often using hand gestures to emphasize her responses, express emotions, and bring clarity to complex explanations. With her friendly personality, Alanna proactively initiates conversations, aiming to anticipate user needs, spark curiosity, and create a more immersive conversational experience."
    })

while True:
    try:
        user_input = input("\nYou: ")
        if user_input.lower() in ["exit", "quit"]:
            print("Goodbye!")
            break

        conversation_history.append({"role": "user", "content": user_input})

        chat_completion = groq_client.chat.completions.create(
            messages=conversation_history,
            model="llama3-70b-8192",
        )

        output = chat_completion.choices[0].message.content
        conversation_history.append({"role": "assistant", "content": output})

        sort_text(output)
        save_history(conversation_history)

    except Exception as e:
        print(f"Error: {e}")
        break
