"""ASGI entrypoint for the StreamServer.

This exposes a FastAPI ``app`` so that you can run the stream server with
uvicorn's ``--reload`` for live updates during UI development.

Usage:
    AGENT_PATH=demos/agents/basic_chatbot.py uv run uvicorn infra_mvp.stream.app:app --host 0.0.0.0 --port 8991 --reload

Note: AGENT_PATH environment variable is required and must point to a Python file containing an agent.
"""

import os
import sys
from pathlib import Path

from infra_mvp.stream.container import create_stream_server
from yera.agents.discovery import load_agent

# Create the container and underlying StreamServer.
# Respect HOST/PORT environment variables so that running via
# `uvicorn infra_mvp.stream.app:app` (as done by the container entrypoint)
# will bind to the intended network interface instead of defaulting to
# 127.0.0.1 which prevents external access from Kubernetes probes.
env_host = os.getenv("HOST", "0.0.0.0")
env_port = int(os.getenv("PORT", "8991"))
agent_path = os.getenv("AGENT_PATH")

if not agent_path:
    print(
        "Error: AGENT_PATH environment variable is required.",
        "Example: AGENT_PATH=demos/agents/basic_chatbot.py",
        file=sys.stderr,
    )
    sys.exit(1)

try:
    agent_wrapper = load_agent(Path(agent_path))
except (FileNotFoundError, ValueError) as e:
    print(f"Error loading agent: {e}", file=sys.stderr)
    sys.exit(1)

_server = create_stream_server(
    agent=agent_wrapper,
    host=env_host,
    port=env_port,
)

# Expose the FastAPI application configured by BaseServer (includes CORS middleware)
app = _server.app
