"""
main()
======

Main entry point for the application.

If mekansm is installed, it can be started by calling `python -m mekansm`.
"""
import argparse
import logging
import pprint
from collections import defaultdict

import cherrypy
import utc
import yaml

from mekansm.adapters import Context
from mekansm.handlers import wsgi_app


def cmd_config():
    """Return a dictionary to update cherrypy.config based on cmd line args"""
    parser = argparse.ArgumentParser(description="Start Mekansm")
    parser.add_argument(
        "port",
        type=int,
        help="The TCP port on which to listen for connections"
    )
    parser.add_argument(
        "yaml_config",
        help="Path of the YAML file used for configuration"
    )
    args = parser.parse_args()
    res = {"server.socket_host": "0.0.0.0"}
    with open(args.yaml_config) as fh:
        res.update(yaml.safe_load(fh))
    res["server.socket_port"] = args.port
    return res


def main(config):
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    logger.info("Starting Mekansm with config: \n%s", pprint.pformat(config))
    setup_statistics()
    cherrypy.config.update(config)
    context = Context(config)
    wsgi_app(context)

    cherrypy.engine.start()
    cherrypy.server.httpserver.stats["Enabled"] = True
    cherrypy.engine.block()


def setup_statistics():
    logging.statistics = getattr(logging, "statistics", {})
    logging.statistics.update({"Mekansm": {}, "Health": {}})
    mstats = logging.statistics["Mekansm"]
    start_time = utc.now()

    def _metric_base():
        def _dur(d):
            seconds = (utc.now() - start_time).seconds
            return (1.0 * d["Events"] / seconds) if seconds else "N/A"
        return {"Events": 0, "Events/Second": _dur}

    mstats["Errors"] = defaultdict(_metric_base)


main(cmd_config())
