"""Edge server entrypoint.

Supports running as ``python -m sage.edge.server`` or via the ``sage-edge``
console script.

The edge server acts as a **pure HTTP reverse proxy**: it forwards all LLM
requests to an externally-running LLM gateway process (sagellm-gateway or any
OpenAI-compatible server) over HTTP.  There is zero in-process Python coupling
to the SageLLM ecosystem -- the two ecosystems interact exclusively via HTTP.

Upstream URL resolution (delegated to :func:`sage.libs.llm.gateway.get_gateway_url`):

1. ``--llm-upstream`` CLI flag.
2. :func:`sage.libs.llm.gateway.get_gateway_url`: explicit registration, then
   ``SAGE_LLM_GATEWAY_URL`` env, then ``http://localhost:{SagePorts.SAGELLM_GATEWAY}``.
"""

from __future__ import annotations

import argparse
import os

import uvicorn

from sage.common.config.ports import SagePorts
from sage.edge.app import create_app


def _parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Run the SAGE edge aggregator")
    parser.add_argument(
        "--host",
        default=os.getenv("SAGE_EDGE_HOST", "0.0.0.0"),
        help="Host interface to bind",
    )
    parser.add_argument(
        "--port",
        type=int,
        default=int(os.getenv("SAGE_EDGE_PORT", SagePorts.EDGE_DEFAULT)),
        help="Port to bind (defaults to SagePorts.EDGE_DEFAULT)",
    )
    parser.add_argument(
        "--llm-prefix",
        type=str,
        default=os.getenv("SAGE_EDGE_LLM_PREFIX"),
        help="Optional path prefix for LLM proxy routes (default: /)",
    )
    parser.add_argument(
        "--llm-upstream",
        type=str,
        default=None,
        help=(
            "Base URL of the running LLM gateway "
            "(default: SAGE_LLM_GATEWAY_URL env or http://localhost:8889)"
        ),
    )
    parser.add_argument(
        "--no-llm",
        action="store_true",
        help="Start edge shell without proxying to an LLM gateway",
    )
    parser.add_argument(
        "--log-level",
        default=os.getenv("SAGE_EDGE_LOG_LEVEL", "info"),
        help="Uvicorn log level (debug, info, warning, error)",
    )
    return parser.parse_args()


def main() -> None:
    args = _parse_args()

    llm_upstream: str | None = None
    if not args.no_llm:
        if args.llm_upstream:
            llm_upstream = args.llm_upstream
        else:
            # Delegate URL resolution to sage.libs.llm.gateway (env / SagePorts default)
            from sage.libs.llm.gateway import get_gateway_url

            llm_upstream = get_gateway_url()

    app = create_app(llm_upstream=llm_upstream, llm_prefix=args.llm_prefix)

    uvicorn.run(
        app,
        host=args.host,
        port=args.port,
        log_level=args.log_level,
    )


if __name__ == "__main__":
    main()
