import os
import json
import openai

# OpenAI API key - read from environment variable
openai.api_key = os.getenv("OPENAI_API_KEY")

# Directory and file paths
base_dir = os.path.dirname(os.path.abspath(__file__)) if '__file__' in globals() else os.getcwd()
response_file = os.path.join(base_dir, "business_responses.json")
prompt_file = os.path.join(base_dir, "generated_prompt.txt")
image_url_file = os.path.join(base_dir, "generated_image_url.txt")

def ask_questions():
    """
    Function to ask the user for input and save it into a JSON file.
    """
    print("Welcome! Please answer the following questions to generate an AI image prompt:")

    # Collect user inputs
    subject = input("Enter the main subject (e.g., a person, object, or scene): ")
    environment = input("Enter the environment (e.g., at home, in a forest, etc.): ")
    mood = input("Enter the mood (e.g., calm, energetic, happy): ")
    style = input("Enter the image style (e.g., minimalist, bold, photographic): ")

    # Create a dictionary to save these inputs
    data = {
        "subject": subject,
        "environment": environment,
        "mood": mood,
        "style": style
    }

    # Save to JSON file
    with open(response_file, "w") as f:
        json.dump(data, f, indent=4)

    print(f"Your answers have been saved to {response_file}")

def generate_prompt():
    """
    Function to generate a text prompt for the AI based on the user's input.
    """
    # Load the user inputs from the JSON file
    if not os.path.exists(response_file):
        print(f"{response_file} does not exist. Please run the questions script first.")
        return

    with open(response_file, "r") as f:
        data = json.load(f)

    # Generate the AI image prompt
    subject = data.get("subject", "something")
    environment = data.get("environment", "an environment")
    mood = data.get("mood", "a mood")
    style = data.get("style", "a style")

    prompt = f"An image of {subject} in a {environment} environment, with a {mood} mood, in {style} style."

    # Save the prompt to a text file
    with open(prompt_file, "w") as f:
        f.write(prompt)

    print(f"The generated prompt has been saved to {prompt_file}:\n{prompt}")

def create_image():
    """
    Function to use the OpenAI API to generate an image based on the saved prompt.
    """
    # Load the prompt from the text file
    if not os.path.exists(prompt_file):
        print(f"{prompt_file} does not exist. Please run the generate_prompt script first.")
        return

    with open(prompt_file, "r") as f:
        prompt = f.read()

    print(f"Using prompt:\n{prompt}")

    # Use the OpenAI API to create the image
    try:
        response = openai.Image.create(
            prompt=prompt,
            n=1,  # Number of images to generate
            size="1024x1024"  # Size of the image
        )
        image_url = response['data'][0]['url']
        print(f"Image generated successfully: {image_url}")

        # Save the image URL to a file
        with open(image_url_file, "w") as f:
            f.write(image_url)
        print(f"Image URL has been saved to {image_url_file}")

    except Exception as e:
        print(f"Error generating image: {e}")

def main():
    """
    Main function to run the entire process:
    1. Ask questions
    2. Generate prompt
    3. Create image using API
    """
    while True:
        print("\nChoose an action:")
        print("1. Ask questions to generate AI prompt")
        print("2. Generate prompt from saved responses")
        print("3. Create image using AI prompt")
        print("4. Exit")

        choice = input("Enter your choice (1-4): ")

        if choice == "1":
            ask_questions()
        elif choice == "2":
            generate_prompt()
        elif choice == "3":
            create_image()
        elif choice == "4":
            print("Exiting...")
            break
        else:
            print("Invalid choice. Please try again.")

if __name__ == "__main__":
    main()