import re

from datasette import hookimpl, Response


def _simplify_pattern(pattern):
    """Convert a regex pattern to a simplified human-readable path.

    Strips anchors, removes optional format suffixes, and replaces
    named groups with {name} placeholders.
    """
    # Remove anchors
    path = pattern.lstrip("^").rstrip("$")
    # Remove optional .format suffixes like (\.(?P<format>json))?
    path = re.sub(r"\(\\\.?\(\?P<format>[^)]*\)\)\?", "", path)
    # Replace named groups (?P<name>...) with {name}
    path = re.sub(r"\(\?P<(\w+)>[^)]*\)", r"{\1}", path)
    # Remove remaining regex artifacts
    path = path.replace("\\.", ".").replace("\\", "")
    # Remove leftover empty parens or optional markers
    path = re.sub(r"\(\)?", "", path)
    return path or "/"


def _get_view_name(view_fn):
    """Extract a human-readable name from a view function."""
    if hasattr(view_fn, "view_class"):
        return view_fn.view_class.__name__
    return getattr(view_fn, "__name__", repr(view_fn))


def _get_endpoints(datasette):
    routes = datasette._routes()
    endpoints = []
    for compiled_regex, view_fn in routes:
        pattern = compiled_regex.pattern if hasattr(compiled_regex, "pattern") else str(compiled_regex)
        path = _simplify_pattern(pattern)
        view_name = _get_view_name(view_fn)
        endpoints.append({
            "path": path,
            "view": view_name,
            "pattern": pattern,
        })
    return endpoints


async def endpoints_json(datasette):
    return Response.json(_get_endpoints(datasette))


async def endpoints_html(request, datasette):
    return Response.html(
        await datasette.render_template(
            "endpoints.html",
            {"endpoints": _get_endpoints(datasette)},
            request=request,
        )
    )


@hookimpl
def register_routes():
    return [
        (r"^/-/endpoints\.json$", endpoints_json),
        (r"^/-/endpoints$", endpoints_html),
    ]
