# companion.py — XBOTNOW. Runs on your computer, never in the browser.
# pip install pyserial openai
# Set OPENAI_API_KEY and OPENAI_MODEL in your environment before running.
import json
import os
import sys

import serial
from openai import OpenAI

model = os.environ.get("OPENAI_MODEL")
if not model or not os.environ.get("OPENAI_API_KEY"):
    sys.exit("Set OPENAI_MODEL and OPENAI_API_KEY before running.")
client = OpenAI(timeout=20.0)

PORT = sys.argv[1] if len(sys.argv) > 1 else "/dev/ttyACM0"   # e.g. COM5 on Windows
esp = serial.Serial(PORT, 115200, timeout=1)

def face(**msg):
    esp.write((json.dumps(msg) + "\n").encode())

SYSTEM = ("You are Pixel, a cheerful desk companion. "
          "Reply in at most 2 short sentences, plain text, no emoji.")

def ask_ai(history):
    """Send typed chat messages from the computer to the OpenAI API."""
    response = client.responses.create(
        model=model,
        input=history,
        max_output_tokens=240,
        store=False,
    )
    return response.output_text.strip() or "I don't have a reply yet."

history = []
face(state="idle")
print("Type a message (Ctrl+C to quit).")
while True:
    text = input("> ").strip()
    if not text:
        continue
    history.append({"role": "user", "content": text})
    face(state="thinking")
    try:
        reply = ask_ai([{"role": "system", "content": SYSTEM}] + history[-10:])
        history.append({"role": "assistant", "content": reply})
        print("Pixel:", reply)
        face(state="speaking", text=reply[:120])
    except Exception as e:
        print("AI request failed:", type(e).__name__)
        face(state="error")
