"""
Server blueprint
Non-API specific endpoints for application management
"""
from logging import Logger
from typing import cast

from flask import Blueprint, Config, Flask, url_for
from injector import inject
from werkzeug.routing import BuildError

application_blueprint = Blueprint("application", __name__)


@inject
@application_blueprint.route("/healthcheck", methods=("GET",))
def healthcheck(log: Logger):
    log.info("Healthcheck")
    return "healthcheck: '{{application.raw_name}}' is running"

@inject
@application_blueprint.route("/", methods=("GET",))
def root(flask: Flask, config: Config, log: Logger):
    # do not allow any requests to / in non-debug environments
    if config['ENV'] != 'development':
        return "", 405

    {#
    TODO this does not group by like-URLs that are used for different methods.
    for example, get_foo() and post_foo() might both use the URL /foo, but the
    HTTP verbs GET (for get_) and POST (for post_). This makes the table look
    awkward, so it may be prudent to think about how to represent that.
    #}
    # in debug environments, print a table of all routes and their allowed methods
    output = "<table><tr><th>url</th><th>methods</th></tr>"
    for rule in flask.url_map.iter_rules():
        try:
            url = url_for(rule.endpoint, **(rule.defaults or {}))
            sep = ""
            output += f"<tr><td>{url}</td><td>"
            for method in sorted(list(cast(set[str], rule.methods))):
                output += sep
                if method == "GET":
                    output += f"<a href=\"{url}\">GET</a>"
                else:
                    output += method
                sep = ", "
            output += "</td></tr>"
        except BuildError as e:
            log.warn(e)

    output += "</table>"

    return output
