import logging

from planemapper.provisioning import ProvisioningError, wifi
from planemapper.provisioning.portal import app

log = logging.getLogger(__name__)


def _reset_to_portal_state() -> None:
    log.info("Resetting to portal state")
    try:
        wifi.stop_ap()
    except Exception:
        pass


def main() -> None:
    logging.basicConfig(level=logging.INFO)
    provisioned = False
    while not provisioned:
        try:
            wifi.start_ap()
            log.info("Portal starting on 0.0.0.0:80")
            app.run(host="0.0.0.0", port=80)
            provisioned = True
        except ProvisioningError as e:
            log.error("Provisioning failed: %s", e)
            _reset_to_portal_state()
