import pygame
import time
from openai import OpenAI

# Initialize OpenAI API key
api_key = 'sk-proj-wwWaxim1Qt13uq5645dfghvbnzSS0xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S'
client = OpenAI(api_key=api_key)

def user_input():
    while True:
        try:
            num = int(input("Enter a number from 1 to 3: "))
            if 1 <= num <= 3:
                return num
            else:
                print("Invalid input. Please enter a number between 1 and 3.")
        except ValueError:
            print("Invalid input. Please enter a valid integer.")

def play_audio(num):
    audio_files = {
        1: "Gigabee.mp3",
        2: "hydrosense.mp3",
        3: "Pushtotalk.mp3",
    }
    
    text_files = {
        1: "Gigabeeprotect.txt",
        2: "Hydrosense.txt",
        3: "Pushtotalk.txt",
    }

    audio_file = audio_files.get(num)
    text_file = text_files.get(num)
    
    if audio_file and text_file:
        pygame.mixer.init()
        pygame.mixer.music.load(audio_file)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            time.sleep(1)

        # Prompt for Q&A mode
        user_choice = input("Would you like to enter Q&A mode? (yes/no): ").strip().lower()
        if user_choice == 'yes':
            with open(text_file, 'r') as file:
                context = file.read()
            start_qa_mode(context)

def start_qa_mode(context):
    while True:
        question = input("Ask a question (or type 'exit' to quit): ").strip()
        if question.lower() == 'exit':
            break
        
        response = client.chat.completions.create(
            engine="text-davinci-003",  # You can choose another engine if needed
            prompt=f"{context}\n\nQuestion: {question}\nAnswer:",
            max_tokens=150
        )
        
        answer = (response.choices[0].message.content)
        print(f"Answer: {answer}")

if __name__ == "__main__":
    while True:
        number = user_input()
        play_audio(number)
        # Loop continues to ask for new user input after Q&A mode ends or if no Q&A mode is entered
