from multiprocessing import Process
import requests
from requests.adapters import HTTPAdapter
from urllib3 import Retry
import uvicorn
import webbrowser


def main(host, port, confpath, reload, debug) -> None:

    server_process = Process(
        target=uvicorn.run,
        args=(f'{confpath}:app',),
        kwargs={
            'app_dir': '..',
            'host': host,
            'port': int(port),
            'log_level': 'debug',
            'reload': reload,
        },
        daemon=(reload is False),
    )
    url = f'http://{host}:{int(port):04d}/status'
    print(url)
    server_process.start()

    try:
        sesh = requests.Session()
        retries = Retry(
            total=5,
            backoff_factor=0.1,
        )
        sesh.mount('http://', HTTPAdapter(max_retries=retries))
        resp = sesh.get(url)
        assert resp.status_code == 200
    except Exception:
        print('Error starting server')
        server_process.terminate()
        exit()

    webbrowser.open(url, new=1, autoraise=True)

    if debug:
        print('Running in debug mode')
    print('Type "STOP" to stop server')
    input_str = ''
    while input_str.upper() != 'STOP':
        input_str = input()

    server_process.terminate()