# coding: utf-8
from django.conf import settings
from django.core.exceptions import DisallowedHost, ImproperlyConfigured
from yarl import URL

REAL_IP_HEADERS = ('HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR')


def get_real_ip(request):
    for header in REAL_IP_HEADERS:
        if header in request.META:
            return request.META[header].split(',')[0]
    return None


def is_internal(request):

    try:
        host = request.get_host()

    except DisallowedHost:
        return False

    if settings.IS_DEVELOPMENT:

        if host.startswith('procu.int'):
            return True

        if host.startswith('procu.ext'):
            return False

        raise ImproperlyConfigured(
            'Invalid host. '
            'Please add `127.0.0.1 procu.int` and `127.0.0.1 procu.ext` '
            'to your /etc/hosts and use these virtual hosts '
            'for internal and external APIs respectively.'
        )

    return 'yandex-team.ru' in host


def get_current_url(
    request, add_params: dict = None, del_params: list = None
) -> str:

    url = URL(request.get_raw_uri())

    if add_params or del_params:
        params = request.GET.copy()
        params.update(add_params or {})

        for p in del_params or ():
            params.pop(p, None)

        url = url.with_query(params)

    return str(url)
