import pygame.mixer as mixer
import speech_recognition as sr
import openai
from pathlib import Path
from openai import OpenAI
import os
import pygame
import mixer

# Set your OpenAI API key here
api_key = 'sk-proj-wwWaxim1Qt13243454353uqzSS0xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S'
client = OpenAI(api_key=api_key)

# Initialize pygame mixer
pygame.mixer.init()
def read_text_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        return file.read()

# Function to recognize speech from the microphone
def recognize_speech():
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = recognizer.listen(source)
        try:
            print("Recognizing...")
            text = recognizer.recognize_google(audio, language='en-US')
            print(f"You said: {text}")
            return text
        except sr.UnknownValueError:
            print("Sorry, I did not understand that.")
            return None
        except sr.RequestError:
            print("Sorry, there was an error with the speech recognition service.")
            return None

# Function to get a response from OpenAI

def create_messages(question, file_content):
    return [
        {"role": "system", "content": "You are a helpful assistant who explains and answers about IoT use cases in Vodafone. Do not say any calculations. Directly say the result"},
        {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
    ]
    
def get_response_from_openai(messages):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=messages,
        max_tokens=150,
        temperature=0.5,
    )
    return  (response.choices[0].message.content)

# Function to generate speech using OpenAI TTS
def generate_speech(text, file_path):
    speech_file_path = Path(file_path).parent / "speech.mp3"
    with client.audio.speech.with_streaming_response.create(
        model="tts-1",  # Replace with your actual model ID
        input=text,
        voice="alloy"  # Replace with a valid voice for your chosen model
    ) as response:
        response.stream_to_file(str(speech_file_path))
    return str(speech_file_path)

# Main function to handle user query
def chatbot(question, file_path):
    file_content = read_text_file(file_path)
    messages = create_messages(question, file_content)
    answer = get_response_from_openai(messages)
    return answer

if __name__ == "__main__":
    file_path = 'device_data.txt'  # Path to your text file
    while True:
        print("Press Enter to ask a question, or type 'exit' or 'quit' to stop.")
        user_input = input("Type 'speak' to ask a question using your voice: ").strip().lower()
        
        if user_input in ['exit', 'quit']:
            break
        
        if user_input == 'speak':
            question = recognize_speech()
            if question:
                answer = chatbot(question, file_path)
                print("Answer:", answer)
                speech_file = generate_speech(answer, file_path)
                pygame.mixer.init()
                pygame.mixer.music.load(speech_file)
                pygame.mixer.music.play()
                while pygame.mixer.music.get_busy():
                 pygame.time.Clock().tick(10)  # Adjust as needed
                pygame.mixer.music.stop()  # Ensure music playback stops
                pygame.mixer.quit()  # Release resources
                os.remove(speech_file)

        else:
            question = user_input
            answer = chatbot(question, file_path)
            print("Answer:", answer)
            speech_file = generate_speech(answer, file_path)
            pygame.mixer.init()
            pygame.mixer.music.load(speech_file)
            pygame.mixer.music.play()
            while pygame.mixer.music.get_busy():
              pygame.time.Clock().tick(10)  # Adjust as needed
            pygame.mixer.music.stop()  # Ensure music playback stops
            pygame.mixer.quit()  # Release resources
            os.remove(speech_file)
