import argparse
import logging
import os
import sys


def get_args(args):
    """
    Parse command line arguments.
    """

    parser = argparse.ArgumentParser(
        description="""Serve a Markdown folder as a web blog.

The folder should have the following structure:

.
  -> config.yaml [recommended]
  -> markdown
    -> article-1.md
    -> article-2.md
    -> ...
  -> img [recommended]
    -> favicon.ico
    -> icon.png
    -> image-1.png
    -> image-2.png
    -> ...

""",
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument(
        "dir",
        nargs="?",
        default=None,
        help="Base path for the blog (default: current directory)",
    )
    parser.add_argument(
        "--config",
        dest="config",
        default="config.yaml",
        required=False,
        help="Path to a configuration file (default: config.yaml in the blog root directory)",
    )
    parser.add_argument(
        "--host",
        dest="host",
        required=False,
        default="0.0.0.0",
        help="Bind host/address",
    )
    parser.add_argument(
        "--port",
        dest="port",
        required=False,
        type=int,
        default=8000,
        help="Bind port (default: 8000)",
    )
    parser.add_argument(
        "--debug",
        dest="debug",
        required=False,
        action="store_true",
        default=False,
        help="Enable debug mode (default: False)",
    )

    return parser.parse_known_args(args)


def run():
    """
    Run the application.
    """

    from .config import init_config

    opts, _ = get_args(sys.argv[1:])
    blog_dir = opts.dir or "."
    config_file = opts.config if opts.config else os.path.join(blog_dir, "config.yaml")
    config = init_config(config_file=config_file, args=opts)
    logging.basicConfig(
        level=logging.DEBUG if config.debug else logging.INFO,
        format="%(levelname)s: %(message)s",
    )

    from .app import app

    try:
        app.start()
        app.run(host=config.host, port=config.port, debug=config.debug)
    finally:
        app.stop()


# vim:sw=4:ts=4:et:
