"""Uvicorn server initialization script.

Run ``python runserver.py --help`` to see the options.
"""

import os
from typing import Optional

import uvicorn
from typer import Typer, Option


cli_app = Typer()


port_help = "Set the port of the uvicorn server."
docker_help = (
    "Use this option to run the server in the Docker container. This will "
    "setup the PostgreSQL server using $POSTGRES_URI instead of "
    "$POSTGRES_LOCAL_URI"
)
auto_reload_server_help = (
    "Equivalent to --reload flag in uvicorn server CLI. WARNING: "
    "if you use this option in the docker container this script will not "
    "gracefully stop the Celery worker process behind the application. "
)


@cli_app.command()
def run_uvicorn_server(
    auto_reload_server: bool = Option(False, help=auto_reload_server_help),
) -> None:
    """Run the FastAPI app using a uvicorn server, optionally setting up and
    tearing down some other overheads such as PostgreSQL db, Celery worker,
    RabbitMQ server, Redis server, etc.
    """

    # Run server
    uvicorn.run(
        "src.main:app",
        host=os.environ.get("API_HOST", "0.0.0.0"),
        forwarded_allow_ips="*",
        port=int(os.environ.get("API_PORT", "8000")),
        reload=auto_reload_server,
        # debug=auto_reload_server,
        workers=int(os.environ.get("API_WORKERS", "1")),
        proxy_headers=True,
    )


if __name__ == "__main__":
    cli_app()
