"""chatbot.py, M4: your first AI app, a tiny chatbot with a personality.

You can read every line. The shape is:
  - keep a list of messages (the conversation so far)
  - each turn: add the user's message, ask Claude, print + remember the reply

Run (inside your activated virtual environment, from this folder, after check_setup.py works):
    python chatbot.py
"""

import os
from dotenv import load_dotenv
import anthropic

load_dotenv()
client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY from the environment

# The SYSTEM prompt sets the bot's personality and rules. Change it to remake the bot!
SYSTEM = (
    "You are Pip, a warm and upbeat assistant for people learning to code. "
    "Keep answers short and encouraging, and use a friendly emoji now and then."
)

messages = []                           # the whole conversation lives here

print("Chat with Pip (type 'quit' to leave)\n")
while True:
    user_text = input("You: ")
    if user_text.strip().lower() in {"quit", "exit"}:
        print("Pip: Bye for now, keep going, you're doing great! ")
        break

    # 1. Add what the user said to the conversation.
    messages.append({"role": "user", "content": user_text})

    # 2. Ask Claude, sending the WHOLE conversation each time (the API is stateless).
    response = client.messages.create(
        model="claude-opus-4-8",
        max_tokens=1024,
        system=SYSTEM,
        messages=messages,
    )

    # 3. Read the reply (the first content block is the text).
    reply = response.content[0].text
    print("Pip:", reply, "\n")

    # 4. Remember the reply, so Pip has context on the next turn.
    messages.append({"role": "assistant", "content": reply})
