"""
Actual application logic for kdlj2.

Handles both main use cases: static rendering and dynamic serving.
"""

import argparse

from .j2env import setup_environment
from .mime import setup_mime
from .server import setup_debug_server
from .static import static_build


def parse_args() -> argparse.Namespace:
    """Parse app specific arguments for kdlj2-web."""
    parser = argparse.ArgumentParser(description="KDL Web Engine")
    subparsers = parser.add_subparsers(dest="command", required=True)

    parser.add_argument(
        "-o",
        "--option",
        "--opts",
        action="append",
        help="Add custom template options which override options.json "
        "(e.g. -o theme=dark)",
    )
    parser.add_argument(
        "-s",
        "--srcdir",
        "--src",
        type=str,
        help="Folder in which to find templates from",
    )

    serve_parser = subparsers.add_parser(
        "serve", help="Serve pages via HTTP in debug mode"
    )
    serve_parser.add_argument(
        "--port", type=int, default=8080, help="Listen port in which to serve HTTP"
    )

    build_parser = subparsers.add_parser("build", help="Generate a static site")
    build_parser.add_argument(
        "--outdir",
        "--out",
        "-d",
        type=str,
        default="dist",
        help="Out path in which to put built files",
    )

    return parser.parse_args()


def main() -> None:
    """Run kdlj2-web as an executable entrypoint."""  # pydocstring is being awkward :(
    setup_mime()

    args = parse_args()

    env = setup_environment(args.srcdir)

    custom_opts = {}
    if args.option:
        for opt in args.option:
            if "=" in opt:
                k, v = opt.split("=", 1)
                custom_opts[k] = v

    if args.command == "build":
        print(f"Building static site to ./{args.outdir}...")
        static_build(env, args.srcdir, args.outdir, custom_opts)
        print("Done!")

    elif args.command == "serve":
        setup_debug_server(env, args.srcdir, args.port, custom_opts).serve_forever()
