"""Main entry point for running StreamServer.

Usage:
    python -m infra_mvp.stream --agent-path demos/agents/basic_chatbot.py
    python -m infra_mvp.stream --agent-path demos/agents/basic_chatbot.py --port 8991
    python -m infra_mvp.stream --agent-path demos/agents/basic_chatbot.py --host 0.0.0.0 --port 8991
"""

import argparse
import os
import signal
import sys
from pathlib import Path

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


def main():
    """Run StreamServer with command-line arguments."""
    parser = argparse.ArgumentParser(
        description="Start StreamServer for SSE streaming to Yera UI"
    )
    default_host = os.getenv("HOST", "0.0.0.0")
    default_port = int(os.getenv("PORT", "8991"))

    parser.add_argument(
        "--agent-path",
        type=str,
        required=True,
        help="Path to Python file containing an agent",
    )
    parser.add_argument(
        "--agent",
        type=str,
        default=None,
        help="Name of the agent to use when multiple agents exist in the file",
    )
    parser.add_argument(
        "--host",
        type=str,
        default=default_host,
        help=f"Server host address (default: {default_host})",
    )
    parser.add_argument(
        "--port",
        type=int,
        default=default_port,
        help=f"Server port number (default: {default_port})",
    )
    parser.add_argument(
        "--debug",
        action="store_true",
        help="Enable debug logging of events to file (logs to yera-debug-<timestamp>.jsonl)",
    )

    args = parser.parse_args()

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

    # Create stream server with Python agent
    server = create_stream_server(
        agent=agent_wrapper,
        host=args.host,
        port=args.port,
        debug=args.debug,
    )

    # Handle graceful shutdown
    def signal_handler(sig, frame):  # noqa: ARG001
        print("\nShutting down server...")
        server.stop()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    # Start server
    print(f"Starting StreamServer on {server.url_base}")
    print("Press Ctrl+C to stop the server")
    print(f"Health check: {server.url_base}/health")
    print(f"API docs: {server.url_base}/docs")

    try:
        with server:
            # Keep server running
            import time

            while True:
                time.sleep(1)
    except KeyboardInterrupt:
        signal_handler(None, None)


if __name__ == "__main__":
    main()
