"""Interactive assistant against the REAL API:  OPENAI_API_KEY=sk-... python cli.py

Type a question about the shop's data; type 'quit' to exit.
"""

import logging
import os
import sys

from openai import OpenAI

from analyst import Assistant, ReadOnlyDB
from analyst.search import ProductSearch


def main() -> None:
    if not os.environ.get("OPENAI_API_KEY"):
        sys.exit("Set OPENAI_API_KEY first (lesson 02), or run the offline demo: python demo.py")
    logging.basicConfig(level=logging.WARNING)
    client = OpenAI(timeout=60, max_retries=2)
    db = ReadOnlyDB()
    print("indexing products for semantic search…")
    assistant = Assistant(client, db, search=ProductSearch(client, db))
    total = 0.0
    while True:
        question = input("\nquestion> ").strip()
        if question.lower() in {"quit", "exit", ""}:
            break
        answer, turn = assistant.ask(question)
        total += turn.cost_usd
        print("\n" + answer.summary)
        for kn in answer.key_numbers:
            print(f"  - {kn.label}: {kn.value}")
        if answer.caveats:
            print("caveats:", "; ".join(answer.caveats))
        print(f"[{len(turn.tool_calls)} tool calls, {turn.input_tokens}+{turn.output_tokens} tokens, "
              f"${turn.cost_usd:.4f}; session ${total:.4f}]")


if __name__ == "__main__":
    main()
