from typing import Any

import aiohttp
from fastapi import Request

from intranet.trip.src.config import settings
from intranet.trip.src.api.auth.tvm import get_tvm_service_ticket_header
from intranet.trip.src.api.auth.oauth import get_oauth_token


FORWARDED_FOR_HEADER = 'X-Forwarded-For-Y'


def get_real_ip(headers: dict[str, str]) -> str:
    return headers.get(FORWARDED_FOR_HEADER)


def get_host(headers: dict[str, str]) -> str:
    for header in ('Host', 'HOST'):
        if header in headers:
            return headers[header]


def get_request_params(request: Request) -> dict[str, Any]:
    params = {
        'dbfields': '',
        'userip': get_real_ip(request.headers) or '',
        'host': get_host(request.headers),
        'emails': 'getdefault',
        'get_user_ticket': 'true',
        'regname': 'yes',
        'aliases': 'all',
        'format': 'json',
        'attributes': settings.blackbox_attributes,
    }

    if 'Session_id' in request.cookies:
        params['method'] = 'sessionid'
        params['sessionid'] = request.cookies.get('Session_id', '')
    elif 'oauth' in request.headers.get('Authorization', '').lower():
        params['method'] = 'oauth'
        params['oauth_token'] = get_oauth_token(request)

    return params


async def get_user_by_request(request: Request) -> dict[str, Any]:
    """
    Возвращает dict с данными сотрудника от Блэкбокса.
    Интересующие нас поля:
    {
        'error': 'OK',
        'uid': {'value': '1120000000018264', 'lite': False, 'hosted': False},
        'login': 'wlame',
        'user_ticket': '3:user:CJFpEJfk9vcFGigKCQjYjpmRpdT-ARDYjpmRp.....',
        ...
    }
    """
    service_headers = await get_tvm_service_ticket_header('passport')
    params = get_request_params(request)

    async with aiohttp.ClientSession(headers=service_headers) as session:
        async with session.get(settings.BLACKBOX_URL, params=params) as response:
            response_data = await response.json()

    return response_data
