from dotenv import load_dotenv
import os
from groq import Groq
import json

# Load environment variables
load_dotenv()


api_keys = [
    os.getenv("GROQ_API_KEY_1"),
    os.getenv("GROQ_API_KEY_2"),
    os.getenv("GROQ_API_KEY_3"),
    os.getenv("GROQ_API_KEY_4"),
    os.getenv("GROQ_API_KEY_5"),
    os.getenv("GROQ_API_KEY_6"),
    os.getenv("GROQ_API_KEY_7"),
    os.getenv("GROQ_API_KEY_8"),
    os.getenv("GROQ_API_KEY_9"),
    os.getenv("GROQ_API_KEY_10"),
    os.getenv("GROQ_API_KEY_11"),
    os.getenv("GROQ_API_KEY_12")
]

current_api_index = 0  # Track the current API key index
client = Groq(api_key=api_keys[current_api_index])

def switch_api_key():
    """Switch to the next available API key in case of failure."""
    global client, current_api_index
    
    current_api_index = (current_api_index + 1) % len(api_keys)
    new_key = api_keys[current_api_index]
    print(f"Switching API key... Current API key: {new_key}")
    print(f"Switching API key...")
    try:
        client = Groq(api_key=new_key)
        return True
    except Exception:
        return False

def reset_api_key():
    """Reset the API key iteration back to the first API key."""
    global client, current_api_index
    current_api_index = 0
    client = Groq(api_key=api_keys[current_api_index])
    print("Resetting API key to the first available key.")
    print(f"Resetting API key to the first available key: {api_keys[current_api_index]}")  # Print the current API key

def get_current_api_key():
    """Get and print the current API key."""
    print(f"Currently using API key: {api_keys[current_api_index]}")



def chat_with_groq(prompt: str, model: str = "llama-3.3-70b-versatile") -> str:
    for _ in range(len(api_keys)):
        try:
            chat_completion = client.chat.completions.create(
                messages=[
                    {"role": "system", "content": "you are a helpful AI engineer assistant."},
                    {"role": "user", "content": prompt}
                ],
                model=model,
            )
            reset_api_key()  # Reset API key iteration on success
            get_current_api_key()  # Print the current API key
            print(f"Prompt length: {len(prompt)} characters, {len(prompt.split())} words")
            content = chat_completion.choices[0].message.content
            if not content:
                print(f"Empty content, full response: {chat_completion}")
                raise ValueError("Empty content in the response")
            return chat_completion.choices[0].message.content
        except Exception as e:
            if not switch_api_key():
                return f"An error occurred: {e}"

# def chat_with_groq(prompt: str, model: str = "llama-3.3-70b-versatile") -> str:
#     try:
#         # Initialize Groq client
#         client = Groq(
#             api_key=os.getenv("GROQ_API_KEY"),
#         )
#         # Create a chat completion
#         chat_completion = client.chat.completions.create(
#             messages=[
#                 {
#                     "role": "system",
#                     "content": "you are a helpful AI engineer assistant."
#                 },
#                 {
#                     "role": "user",
#                     "content": prompt
#                 }
#             ],
#             model=model,
#         )
#         # Return the response content
#         print(chat_completion.choices[0].message.content)
#         return chat_completion.choices[0].message.content
#     except Exception as e:
#         return f"An error occurred: {e}"

def chat_with_interviewer_groq(prompt: str) -> str:
    for _ in range(len(api_keys)):
        try:
            completion = client.chat.completions.create(
                model="llama-3.3-70b-versatile",
                messages=[
                    {"role": "system", "content": "You are an expert interviewer providing structured interview evaluations."},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.7,
                max_completion_tokens=1500,
                top_p=1,
                stream=False,
            )
            reset_api_key()  # Reset API key iteration on success
            return completion.choices[0].message.content
        except Exception as e:
            if not switch_api_key():
                return f"An error occurred: {e}"

def transcribe_audio(audio_path):
    for _ in range(len(api_keys)):
        try:
            with open(audio_path, "rb") as file:
                transcription = client.audio.transcriptions.create(
                    file=file,  
                    model="whisper-large-v3-turbo",  
                    prompt="Specify context or spelling",  
                    response_format="json",  
                    language="en",  
                    temperature=0.0  
                )
            reset_api_key()  # Reset API key iteration on success
            return transcription.text
        except Exception as e:
            if not switch_api_key():
                return f"An error occurred: {e}"


def groq_module_fun(resume_prompt, base64_image):
    for _ in range(len(api_keys)):
        try:
            completion = client.chat.completions.create(
                # model="llama-3.2-90b-vision-preview",
                model="meta-llama/llama-4-scout-17b-16e-instruct",
                messages=[
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "text",
                                "text": resume_prompt
                            },
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": f"data:image/jpeg;base64,{base64_image}",
                                },
                            }
                        ]
                    }
                ],
                temperature=1,
                max_completion_tokens=1024,
                top_p=1,
                stream=False,
                response_format={"type": "json_object"},
            )
            
            # Access the response here inside the function
            api_response = completion.choices[0].message.content
            return api_response
        except Exception as e:
            if not switch_api_key():
                return f"An error occurred: {e}"
            
