import os
from openai import OpenAI

# Use environment variable or paste your key
client = OpenAI(api_key="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")  # Replace this with your actual key or use os.getenv()

def start_conversation(theme: str, initial_message: str = "", num_turns: int = 6):
    system_prompt = f"""
You are simulating a realistic, role-based dialogue between two or more characters based on the theme:
'{theme}'

- Automatically identify suitable roles and character types based on the theme.
- Create natural, engaging, and consistent back-and-forth conversation between the characters.
- Clearly indicate who is speaking (e.g., 'Alex (Doctor): Hello...')
- Keep each message short and natural, like real human dialogue.

Begin the conversation now.
"""

    conversation = [
        {"role": "system", "content": system_prompt},
    ]

    if initial_message:
        conversation.append({"role": "user", "content": initial_message})
    else:
        conversation.append({"role": "user", "content": "Start the conversation."})

    for _ in range(num_turns):
        response = client.chat.completions.create(
            model="gpt-4",  # Or gpt-3.5-turbo
            messages=conversation
        )

        reply = response.choices[0].message.content
        print(reply)
        conversation.append({"role": "assistant", "content": reply})

        user_input = input("\n[Press Enter to continue automatically or type next message]: ").strip()
        if user_input:
            conversation.append({"role": "user", "content": user_input})
        else:
            conversation.append({"role": "user", "content": "Continue the conversation."})


# ==== Entry point ====
if __name__ == "__main__":
    theme_input = input("Enter the theme for the conversation: ")
    initial_msg = input("Start the first line (optional): ")
    start_conversation(theme=theme_input, initial_message=initial_msg)
