# Copyright © 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 helpers."""

import contextlib
from collections.abc import Generator
from urllib.parse import ParseResult, urlunparse

from django.conf import settings
from django.urls import get_urlconf, set_urlconf


def make_absolute_webui(path: str) -> str:
    """Make the path absolute and pointing to the main debusine UI."""
    scheme = settings.DEBUSINE_URL_SCHEME
    fqdn = settings.DEBUSINE_FQDN
    return urlunparse(ParseResult(scheme, fqdn, path, "", "", ""))


def make_absolute_archives(path: str) -> str:
    """Make the path absolute and pointing to the UI for archives."""
    if settings.DEBUG:
        return "/-/__archives__" + path
    else:
        scheme = settings.DEBUSINE_DEBIAN_ARCHIVE_URL_SCHEME
        fqdn = settings.DEBUSINE_DEBIAN_ARCHIVE_PRIMARY_FQDN
        return urlunparse(ParseResult(scheme, fqdn, path, "", "", ""))


@contextlib.contextmanager
def urlconf_archives() -> Generator[None]:
    """Temporarily set the scope for reverse URL resolution."""
    orig = get_urlconf()
    try:
        # Note that this does the right thing also with threads and channels,
        # since Django's set_urlconf is backed by asgiref.local.Local.
        set_urlconf("debusine.web.archives.urls")
        yield
    finally:
        set_urlconf(orig)
