#!/usr/bin/env python
import os
import subprocess

import click
import waitress

from api import app, logger

_logger = logger.setup(__name__)

HOST = os.environ["BACKEND_HOST"]
PORT = os.environ["BACKEND_PORT"]


@click.command()
@click.option("--production", is_flag=True)
def start(production):
    """Start backend server.

    Parameters
    ----------
    production : bool, optional
        Defaults to False.
    """
    _logger.info(
        "Starting backend server:\n\tProduction: %s\n\tHost: %s\n\tPort: %s",
        production,
        HOST,
        PORT,
    )

    subprocess.check_call(["python", "setup.py", "install"])
    if production:
        waitress.serve(app.app, host=HOST, port=PORT)

    else:
        # environment variable "FLASK_APP" must be set
        subprocess.check_call(["flask", "run", "--host", HOST, "--port", PORT])


if __name__ == "__main__":
    start()
