from openai import OpenAI
import os
api_key = "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"
client = OpenAI(api_key=api_key)

def generate(path:str):
    """Reads prompt.txt, generates Python code using OpenAI, and stores the response in prompt.txt."""
    file_path = os.path.join(os.getcwd(), path)

    if not os.path.exists(file_path):
        raise FileNotFoundError(f"Prompt file not found: {file_path}")

    with open(file_path, 'r', encoding='utf-8') as file:
        prompt = file.read().strip()

    if not prompt:
        raise ValueError("Prompt file is empty.")

    # Generate code using OpenAI API
    completion = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "You are a helpful Python coding assistant. You expert in optimizing codes and explaining the concepts used in the code."},
            {"role": "user", "content": prompt}
        ],
    )

    response_text = completion.choices[0].message.content.strip()

    # Store response in prompt.txt
    with open(file_path, "w", encoding="utf-8") as file:
        file.write(response_text)

    return response_text
