"""app.py: stream the agent to a browser over Server-Sent Events (SSE).

SSE is the simplest way to push a live event stream to a web page: the response stays open and each
event is sent as a `data: <json>\\n\\n` line. A browser's EventSource (or any client) reads them as
they arrive, so the UI updates live. This is the same event stream from streaming_agent.py, serialized.

    uvicorn app:app --reload
    curl -N -X POST localhost:8000/chat/stream -H 'Content-Type: application/json' -d '{"message":"Who leads billing?"}'

build_client returns the offline mock so this runs without a key; in production, return a client that
wraps the real SDK streaming API (M6) behind the same .turn interface.
"""

import json
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from streaming_agent import StreamingAgent
from mockmodel import make_mock_client

app = FastAPI(title="Streaming Agent")


def build_client():
    return make_mock_client()       # swap for a real SDK-streaming client in production


class ChatIn(BaseModel):
    message: str


@app.get("/health")
def health():
    return {"status": "ok"}


@app.post("/chat/stream")
def chat_stream(req: ChatIn):
    agent = StreamingAgent(build_client())

    def sse():
        for ev in agent.chat_stream(req.message):
            yield f"data: {json.dumps(ev)}\n\n"        # SSE frame: one event per data line

    return StreamingResponse(sse(), media_type="text/event-stream")
