# Copyright 2019, 2021-2022 The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""
debusine URL Configuration.

Debusine supports multi-tenancy by setting the current scope using the
`/{scope}/` prefix at the beginning of most URLs.

This is implemented in Django by using a middleware to detect the scope from
URL, and then setting `request.urlconf` to point to the urlconf to use to
resolve URLs for that scope.

To ease transition from legacy unscoped URLs, generated urlconfs contain
unscoped versions of URL paths that redirect to their scoped versions.

API calls use the unscoped `/api/` prefix in URLs. Scope for API calls is
provided using the `X-Debusine-Scope: name` HTTP header. If the header is
missing, Debusine will use the `DEBUSINE_DEFAULT_SCOPE` setting.

`/admin/` and `/api-auth/` do not need a default scope to work, and are thus
left unscoped.

To prevent ambiguity, scope names are validated against a list of reserved
keywords, which contains prefixes used for non-scoped URLs.
"""
from typing import Any

from django.conf import settings
from django.contrib import admin
from django.urls import include, path, re_path
from django.views.generic import RedirectView

# from django.conf import settings

# if settings.DEBUG:
#     import debug_toolbar


def make_urlpatterns(scope: str) -> list[Any]:
    """
    Create the URL structure of the website given a scope name.

    This is used by ScopeMiddleware to create a different urlconf for each
    scope, to be set it in request.urlconf when the scope is known.
    """
    return [
        path('api/', include('debusine.server.urls', namespace='api')),
        path("", include("debusine.web.urls.homepage", namespace="homepage")),
        re_path(
            fr"^{scope}/(?:workspace)/(?P<path>.+)",
            RedirectView.as_view(
                url=f"/{scope}/%(path)s",
                permanent=True,
                query_string=True,
            ),
        ),
        path(f"{scope}/", include('debusine.web.urls')),
        path("admin/", admin.site.urls),
        path(
            'api-auth/',
            include('rest_framework.urls', namespace='rest_framework'),
        ),
        re_path(
            r"^(?P<path>(?:accounts|work-request|workers|workspace|"
            r"artifact|user|task-status)/.+)",
            RedirectView.as_view(
                url=f"/{settings.DEBUSINE_DEFAULT_SCOPE}/%(path)s",
                permanent=True,
                query_string=True,
            ),
        ),
    ]


# Default urlpatterns
urlpatterns = make_urlpatterns(settings.DEBUSINE_DEFAULT_SCOPE)
