"""Lab 02 - A lightweight multi-turn chat client.

Objective 2.1 - Create a lightweight chat client application by using the Foundry SDK.

Shows the difference between STATELESS calls and a STATEFUL conversation --
the single most likely code-reading question on the exam.

Run:  python 02_chat_client.py
"""
from _common import banner, get_clients, require

MODEL = require("MODEL_DEPLOYMENT")
SYSTEM = "You are a concise travel assistant. Answer in under 40 words."

_, openai = get_clients()

banner("Part A - STATELESS: no conversation id, so no memory")

first = openai.responses.create(
    model=MODEL, instructions=SYSTEM, input="What is the capital of Portugal?"
)
print("Q: What is the capital of Portugal?\nA:", first.output_text)

second = openai.responses.create(
    model=MODEL, instructions=SYSTEM, input="What is its population?"
)
print("\nQ: What is its population?\nA:", second.output_text)
print("\n  ^ The model has no idea what 'its' refers to. No history was passed.")

banner("Part B - STATEFUL: pass conversation=<id> on every call")

conversation = openai.conversations.create()
print(f"Conversation id: {conversation.id}\n")

for question in ("What is the capital of Portugal?", "What is its population?"):
    reply = openai.responses.create(
        model=MODEL,
        instructions=SYSTEM,
        input=question,
        conversation=conversation.id,   # <-- this one argument is the whole lesson
    )
    print(f"Q: {question}\nA: {reply.output_text}\n")

print("  ^ 'its' now resolves, because the conversation carries the history.")

banner("Part C - Interactive REPL (blank line or 'quit' to exit)")

session = openai.conversations.create()
while True:
    try:
        user = input("\nyou > ").strip()
    except (EOFError, KeyboardInterrupt):
        break
    if not user or user.lower() in {"quit", "exit"}:
        break
    answer = openai.responses.create(
        model=MODEL, instructions=SYSTEM, input=user, conversation=session.id
    )
    print("bot >", answer.output_text)

print("\nDone. Exam anchor: conversation=<id> is what makes a call stateful.")
