# coding: utf-8

import secrets
from typing import NamedTuple

from django.conf import settings
from yarl import URL

from procu.api.utils import is_internal


def _common_csp_header(policies: dict) -> str:
    header_parts = []

    for name, policy in policies.items():
        if name in settings.CSP_ALLOWED_POLICIES:
            header_parts.append(f'{name} {" ".join(policy)}')

    return '; '.join(header_parts)


class CSP(NamedTuple):
    nonce: str
    header: str


def get_csp_header(request):

    if is_internal(request):
        header = _common_csp_header(settings.CSP_POLICIES_INTERNAL)
    else:
        header = _common_csp_header(settings.CSP_POLICIES_EXTERNAL)

    nonce = secrets.token_hex(16)
    header = header.format(nonce=nonce)

    # ------------------------------------------------
    # Generate and append report-uri

    report_params = {'from': settings.CSP_SERVICE_NAME}

    if is_internal(request):
        cookies = request.COOKIES

        if 'yandex_login' in cookies:
            report_params['yandex_login'] = cookies['yandex_login']

        if 'yandexuid' in cookies:
            report_params['yandexuid'] = cookies['yandexuid']

    report_uri = URL(settings.CSP_REPORT_URI).with_query(report_params)

    header = f'{header}; report-uri {report_uri};'

    # ------------------------------------------------

    return CSP(nonce=nonce, header=header)
